素数:除了1和它本身之外再无其他因数
下面给出几种用c语言编写程序打印100~200之间的素数的方法:
#include<stdio.h> #include<windows.h> int main() { int i = 0; int count = 0; for (i = 100; i <= 200; i++) { int j = 2; for (j = 2; j <= i - 1; j++) { if (i%j == 0) { break; } } if (j == i) { count++; printf(" %d", i); } } printf("\ncount=%d", count); system("pause"); return 0; }
第二种:因为偶数的因数除1和它本身之外还有2,所以排除100~200之间的偶数
#include<stdio.h> #include<windows.h> int main() { int i = 0; int count = 0; for (i = 101; i <= 200; i+=2) { int j = 2; for (j = 2; j <= i - 1; j++) { if (i%j == 0) { break; } } if (j == i) { count++; printf(" %d", i); } } printf("\ncount=%d", count); system("pause"); return 0; }
第三种:
(i/2)为i整除2
#include<stdio.h> #include<windows.h> int main() { int i = 0; int count = 0; for (i = 100; i <= 200; i++) { int j = 2; for (j = 2; j <= (i/2); j++) { if (i%j == 0) { break; } } if (j>(i/2)) { count++; printf(" %d", i); } } printf("\ncount=%d", count); system("pause"); return 0; }
第四种:综合之前的,给出优化
用到数学中的开方sqrt
#include<stdio.h> #include<math.h> #include<windows.h> int main() { int i = 0; int count = 0; for (i = 101; i <= 200; i+=2) { int j = 0; for (j = 2; j <= sqrt(i); j++) { if (i%j == 0) { break; } } if (j>sqrt(i)) { count++; printf(" %d", i); } } printf("\ncount=%d", count); system("pause"); return 0; }