Prime numbers: have no other factors than 1 and itself
Here are several ways to write a program in C language to print the prime numbers between 100 and 200:
The first: use two for loops to achieve
#include<stdio.h> #include<windows.h> intmain() { 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; }
The second: because the even number has a factor of 2 in addition to 1 and itself, so exclude the even numbers between 100 and 200
#include<stdio.h> #include<windows.h> intmain() { 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; }
The third:
(i/2) is i divisible by 2
#include<stdio.h> #include<windows.h> intmain() { 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; }
Fourth: Before synthesis, give optimization
Use square root sqrt in mathematics
#include<stdio.h> #include<math.h> #include<windows.h> intmain() { 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; }