accomplish:
#include<stdio.h>
using namespace std;
const int MAX_N=1e8;
int prime[MAX_N],cnt;
bool st[MAX_N];//使用bool数组节省空间
void is_prime(int n){
for(int i=2;i<=n;++i){
if(!st[i])prime[cnt++]=i;
for(int j=0;prime[j]<=n/i;++j){
st[i*prime[j]]=1;
if(i%prime[j]==0)break;
}
}
}
int main(){
int n;
is_prime(n);
return 0;
}
Each composite number is only sieved by its smallest prime factor.
Now prove that break is needed when i%prime[j]==0:
S(smaller) is used below to represent the number smaller than j, and L(larger) is used to represent the number greater than j.
- The smallest prime factor of i × Prime[s] is indeed Prime[s].
- The smallest prime factor of i × Prime[L] must be Prime[j] instead of Prime[L].
This means that if j continues to increase (Prime[L] will be used to sieve i × Prime[L], and at this time the minimum prime factor of i × Prime[L] is not Prime[L] but Prime[j]), so should jump out;