This is a practice problem on spoj.com http://www.spoj.com/problems/PRIME1/ ..
my submission gives "time limit exceeded"
constraints are : 1 <= m <= n <= 1000000000, n-m<=100000 time limit for maximum 10 test cases : 6 s
I wrote the following code based on the sieve of eratosthenes ,
void sieve(int m,int n)
{
bool prime[1000005];
bool prime2[1000005];
int i;
int k;
prime[0]=1;
prime[1]=1;
int mi=sqrt(n);
for (int i=2; i<=mi; i++)
if (prime[i]==0)
for ( k=i*i; k<=n; k+=i)
{
if(k<=mi)
prime[k]=1;
if(k>=m)
{
prime2[k-m]=1;
}
}
int u=min(n,(int)1000000);
for(i=0;i<u;i++){
if(prime2[i]==0 && i+m>=2 && i+m<=n)
printf("%d\n",i+m);
}
printf("\n");
}
here 'm' and'n' are the range of numbers between which we have to generate prime numbers.
The problem i'm facing is when I take input as 100000000 100100000 it takes 1.04 s to run (ideone.com C++ 4.3.2) and for 10000000 10100000 it takes 0.07 s
1) why the huge difference between the times , what is contributing to this ?
2) Is there an even faster way to approach this problem ?