You can do this faster using a nearly optimal trial division sieve in one (long) line like this:
Enumerable.Range(0, Math.Floor(2.52*Math.Sqrt(num)/Math.Log(num))).Aggregate(
Enumerable.Range(2, num-1).ToList(),
(result, index) => {
var bp = result[index]; var sqr = bp * bp;
result.RemoveAll(i => i >= sqr && i % bp == 0);
return result;
}
);
The approximation formula for number of primes used here is p(x) < 1.26 x / ln(x)
. We only need to test by primes not greater than x = sqrt(num)
.
Note that the sieve of Eratosthenes has much better run time complexity than trial division (should run much faster for bigger num
values, when properly implemented).