Syntax-wise, you're making two mistakes in your code:
- A
return
in a lambda doesn't return from the enclosing method, just from the lambda, so yourreturn false;
wouldn't work correctly. - You can't
break
out of lambda. Even if that lambda is executed in a loop, that loop is basically invisible to you, you certainly can't control it directly.
I think the best way to fix your code is to use a LINQ method made exactly for this purpose: Any()
, along with TakeWhile()
to filter out the primes that are too large:
static bool IsPrime(long p)
{
double rootP = Math.Sqrt(p);
return !primes.AsParallel().TakeWhile(q => q > rootP).Any(q => p % q == 0);
}
But there is also a flaw in your reasoning:
This, to me, seems like a good candidate for parallelism, since the checking of each known prime against the candidate prime is an independent process.
It's not as simple as that. Checking each prime is also an extremely simple process. This means that the overhead of simple parallelization (like the one I suggested above) is likely to be bigger than the performance gains. A more complicated solution (like the one suggested by Matthew Watson in a comment) could help with that.