step1: 初始化一个a数组,从a[2] 到a[100]以内都为自己。
step2:对每个数,如果可以被2,3,5,7,11,13..(素数)整除则该数设为0,(因为素数的倍数是可以被除1和本身以外的其它数整除,是合数)。
step3:打印出所有非0的数,即为素数。
代码改自爱课程《C语言程序设计》--苏小红老师:
#include <iostream>
#include <cmath>
using namespace std;
const int N = 100;
int main() {
int a[N + 1];
for(int i = 2; i <= N; i++) {
a[i] = i;
}
for(int i = 2; i <= sqrt(N); i++) {
for(int j = i + 1; j <= N; j++) {
if(a[i] != 0 && a[j] != 0 && a[j] % a[i] == 0) {
a[j] = 0;
}
}
}
//Output
int cnt = 0; // count number
for(int i = 2; i <= N; i++) {
if(a[i] != 0) {
printf("%d\t", a[i]);
cnt++;
}
}
cout << endl << endl;
cout << "The number of prime between 2~" << N << " is " << cnt << endl;
return 0;
}
打印结果: