sieve of eratosthenes - SPOJ Prime generator Wrong Answer -
here link problem-:http://www.spoj.com/problems/prime1/. problem asks find prime numbers between given rang 1 <= m <= n <= 1000000000
, n-m<=100000
. have implemented segmented sieve here logic-: problem has maximum value of 10^9, find primes withing square_root(10^9) around 31622.
#include<iostream> #include<cstdio> #include<cmath> using namespace std; void prime1(long int low, long int high, bool* pre) { bool prime[high-low+1]={0}; if(low==high) {if(pre[low]==0)printf("%ld\n", low);return;} int t=sqrt(high); for(long int i=2;i<=t;i++) { if(pre[i]==1)continue; long int a=ceil(((double)low/i))*i;// start value long int b=floor(((double)high/i))*i;// end value if(a==1) continue; if(a==i) a+=i; if(a==0) a=2*i; for(long int x=a;x<=high;x+=i) { prime[x-low]=1; } } if(low==1) prime[0]=1; else if(low==0) prime[0]=prime[1]=1; for(int i=0;i<=(high-low);i++) if(!prime[i])printf("%ld\n", i+low); } int main() { bool pre[32001]; pre[0]=pre[1]=1; int x=sqrt(32001); for(int i=2;i<=x;i++) { if(pre[i]==0) { for(int j=i;i*j<=32000;j++) { pre[i*j]=1; } } } int t; scanf("%d",&t); long low, high; while(t--) { scanf("%ld %ld",&low, &high); printf("\n") prime1(low, high, pre); } }
now i'll start i=2 , find multiples between m , n. here m , n represent low , high respectively. i'll keep on increasing till i<=sqrt(n)
example, m=125 , n=140 a=((double)m/i)*i. i'll consider ceiling value. so, when m=125
i=2
a=126
. so, 126+(2*k)
composite k>=0. same i=3,5,7.....
when submit on spoj, gives me wa. have used spoj toolkit contained test cases. compared other code , getting same result. missing?
Comments
Post a Comment