标签:
5 10 11 0
2 3 5 2 3 5 7 2 3 5 7 11
1 #include <iostream> 2 #include<stdio.h> 3 #include <cstring> 4 using namespace std; 5 6 const int MAXN = 2000000; 7 bool u[MAXN]; 8 int prime[MAXN], cnt = 0; 9 void primer(){ 10 memset(u, true, sizeof(u)); 11 for(int i=2; i<MAXN; ++i){ 12 if(u[i]) prime[cnt++] = i; 13 for(int j=0; j<cnt && i*prime[j]<MAXN; ++j){ 14 u[i*prime[j]] = false; 15 if(0 == i%prime[j]) break; 16 } 17 } 18 } 19 // 20 int getnum(int n){ 21 int left = 0,right = cnt-1; 22 int middle=(left+right)/2 ; 23 while(prime[middle]!=n&&right>=left ){ 24 if(n<prime[middle]) right = middle-1; 25 else left= middle+1; 26 middle = (left+right)/2; 27 } 28 return middle; 29 } 30 31 int main(){ 32 int n; primer(); 33 while(1){ 34 scanf("%d",&n); 35 if(n==0) break; 36 for(int i=0;i<getnum(n )+1;i++ ){ 37 printf("%d ",prime[i] ) ; 38 } 39 printf("\n"); 40 } 41 return 0; 42 }
下面曝一种其他同学的写法:也是筛法,但是比较单一,比较简单,但是却能AC。
1 #include<stdio.h> 2 3 int main(){ 4 int n,i,s,j; 5 bool a[2000005]={0}; 6 a[0]=1;a[1]=1; 7 8 //并没有考虑可能重复筛选的数字 9 for(i=2;i<2000001;i++){ 10 if(a[i]==0){ 11 for(j=i+i;j<=2000001;j=j+i) 12 a[j]=1; 13 } 14 } 15 16 while(scanf("%d",&n)!=EOF&&n!=0){ 17 s=0; 18 for(i=2;i<=n;i++){ 19 if(a[i]==0){ 20 s++; 21 if(s==1) printf("%d",i); 22 if(s>1) printf(" %d",i); 23 } 24 } 25 printf("\n"); 26 } 27 return 0; 28 }
标签:
原文地址:http://www.cnblogs.com/liugl7/p/5363002.html