标签:style blog class code java c
1 /** 2 给定一定范围求其内的素数 3 4 注意: 5 **/ 6 7 #include <iostream> 8 #include <math.h> 9 #include <cstring> 10 using namespace std; 11 #define maxn 1000000 12 long long prime[500000]; 13 long long cprime[500000]; 14 long long isprime[maxn+100]; 15 long long vis[maxn+100]; 16 long long q; 17 void getprime(){ 18 //memset(isprime,0,sizeof(isprime)); 19 q =-1; 20 long long i,j; 21 isprime[0] = isprime[1] =1; 22 for(i=2;i<maxn;i++){ 23 if(!isprime[i]) 24 prime[++q] = i; 25 for(j=0;j<=q&&prime[j]*i<maxn;j++){ 26 isprime[prime[j]*i] =1; 27 if(i%prime[j]==0) 28 break; 29 } 30 } 31 } 32 33 long long qt; 34 void getprime1(long long a, long long b){ 35 qt =-1; 36 if(b<maxn){ 37 for(long long i=a;i<=b;i++){ 38 if(!isprime[i]) 39 cprime[++qt] = i; 40 } 41 }else{ 42 memset(vis,0,sizeof(vis)); 43 long long i,k; 44 for(i=0;i<=b-a;i++){ 45 vis[i] =1; 46 } 47 for(i=0;prime[i]*prime[i]<=b&&i<=q;i++){ 48 k = a/prime[i]; 49 if(k*prime[i]<a) k++; 50 if(k<=1) k++; 51 while(k*prime[i]<=b){ 52 vis[k*prime[i]-a] =0; 53 k++; 54 } 55 } 56 for(i=0;i<=b-a;i++){ 57 if(vis[i]==1) 58 cprime[++qt] = i+a; 59 } 60 } 61 62 } 63 int main() 64 { 65 getprime(); 66 //for(int i=0;i<10;i++) 67 // cout<<prime[i]<<endl; 68 long long a,b; 69 while(cin>>a>>b){ 70 long long maxnum =-1; 71 long long minnum =0x3f3f3f3f; 72 getprime1(a,b); 73 long long max1,max2,min1,min2; 74 // for(int i=0;i<=qt;i++) 75 // cout<<cprime[i]<<endl; 76 for(long long i=0;i<qt;i++){ 77 long long temp = cprime[i+1]-cprime[i]; 78 if(temp>maxnum){ 79 maxnum =temp; 80 max1 = cprime[i]; 81 max2 = cprime[i+1]; 82 } 83 if(temp<minnum){ 84 minnum =temp; 85 min1 = cprime[i]; 86 min2 = cprime[i+1]; 87 } 88 } 89 if((qt+1)<=1) 90 cout<<"There are no adjacent primes."<<endl; 91 else 92 cout<<min1<<","<<min2<<" are closest, "<<max1<<","<<max2<<" are most distant."<<endl; 93 } 94 return 0; 95 }
poj 2689 大范围内素数筛选,布布扣,bubuko.com
标签:style blog class code java c
原文地址:http://www.cnblogs.com/Bang-cansee/p/3724272.html