← Back to topics
Topic

z-nextprime problem

q
qwer1234
I tried to solve the problem using sieve of eratosthenes but it works only for the first 5 test cases.
The problem is i think that i can find the next prime number till 100.000 and the task says till 2000.000.000 here is my code:

#include <stdio.h>
#define n 100000
long a[n+1];
int main(void)
{
long int scanned;
scanf("%li",&scanned);
long i,j;
for(i=2;i<=n;i++)
{
a[i]=1;
}
for(i=2;i<=n;i++)
{
for(j=2;j<=n/i;j++)
{
a[i*j]=0;
}
}
for(i=2;i<=n;i++)
{

if(a[i]==1&&i>scanned&&i%2!=0)
{
printf("%ld",i);
break;
}
}
return 0;
}

Thanks a lot by the way
K
Kameleon
first it shouldn't be a==1 but a[i]==1
but thats just a minor problem
d
demjan0001
well you get TLE probably, well in this task it's enough to go with for loop and just check for every number, but i solved this task with 6k+1 and 6k-1 ... i hope i helped ...
A
Amtrix
You don't need to use the sieve of eratosthen. It is enough to find the prime on this way:

bool IsPrime( long long n )
{
static long long i;
if(n>2 && !(n%2) )return false;
for(i=3;i*i<=n;i+=2)
if( !(n%i) )
return false;
return true;
}
K
Kameleon
i got it thanks @demjan0001 and @Amtrix
K
Kameleon
amtrix's way was really easy even I could solve it .
p
pr0ton
use sieve till 1e6 and beyond that use Amitrix method, use the best of both world,

i used Miller Rabin primality testing :D