I’m a beginner in C#, I’m trying to write an application to get primes between two numbers entered by the user. The problem is: At large numbers (valid numbers are in the range from 1 to 1000000000) getting the primes takes long time and according to the problem I’m solving, the whole operation must be carried out in a small time interval. This is the problem link for more explanation:
SPOJ-Prime
And here’s the part of my code that’s responsible of getting primes:
public void GetPrime()
{
int L1 = int.Parse(Limits[0]);
int L2 = int.Parse(Limits[1]);
if (L1 == 1)
{
L1++;
}
for (int i = L1; i <= L2; i++)
{
for (int k = L1; k <= L2; k++)
{
if (i == k)
{
continue;
}
else if (i % k == 0)
{
flag = false;
break;
}
else
{
flag = true;
}
}
if (flag)
{
Console.WriteLine(i);
}
}
}
Is there any faster algorithm?
Thanks in advance.
I remember solving the problem like this:
sqrt(1000000000) = ~32 000in an arrayprimes.xbetweenmandnonly test if it’s prime by testing for divisibility against numbers<= sqrt(x)from the arrayprimes. So forx = 29you will only test if it’s divisibile by2, 3 and 5.There’s no point in checking for divisibility against non-primes, since if
x divisible by non-prime y, then there exists a primep < ysuch thatx divisible by p, since we can writeyas a product of primes. For example,12is divisible by6, but6 = 2 * 3, which means that12is also divisible by2or3. By generating all the needed primes in advance (there are very few in this case), you significantly reduce the time needed for the actual primality testing.This will get accepted and doesn’t require any optimization or modification to the sieve, and it’s a pretty clean implementation.
You can do it faster by generalising the sieve to generate primes in an interval
[left, right], not[2, right]like it’s usually presented in tutorials and textbooks. This can get pretty ugly however, and it’s not needed. But if anyone is interested, see:http://pastie.org/9199654 and this linked answer.