Can someone look over this Sieve of Eratosthenes implementation? It seems almost too easy.
Rather than maintaining a seperate bit[]
to track prime/not prime, I'm just removing the noncandidates from the collection completely on each iteration.
Pseudocode
LIST = 2...n
set M = 1
while M < sqrt(n)
set M = next number in LIST > M
remove all multiples of M (excluding M itself) from LIST
C#
int cur = 1, total = 1000;
var pc = Enumerable.Range(2, total).ToList();
while(cur <= Math.Sqrt(total))
{
cur = pc.First(i => i > cur);
pc.RemoveAll(i => i != cur && i % cur == 0);
}
Console.WriteLine(pc.Max());
It just seems a bit too easy. Results seem right though. In LINQPad 4
- Runs
total = 100000;
in 0.008 secs - Runs
total = 1000000;
in 0.141 secs - Runs
total = 10000000;
in 2.973 secs
Math.Sqrt()
isn't the quickest of functions, and the return value used here is effectively constant. Remove it from the comparison, and assign the results to a local variable instead (which can be used in the comparison). I do not believe the compiler is smart enough to catch this... it wasn't when my flatmate tried this. \$\endgroup\$