Why are you saving square root in a double ? You are doing so many comparisons which is involving this and so it is performing slow. If you have saved the Sqrt(primeTest) value in a uint or long instead of double then you must have saved a lot of time. According to me the running time for the first 100 prime numbers after 10^15 will go down by 72 to 48 seconds if you do so as I said. Calculations on uint or long is a good deal faster than floating point as double. It is part redundant variables and code lines here. For example, when you find a number that is not a prime number, you can not just return false right away? Should disappear 429000000 [01] stuff, test variable disappears and all tests after the loop disappears. I've rename it to IsPrime, since that is what it returns:
Code:
static bool IsPrime (this ulong primeTester)
{
var squareRt = (uint)Math.Ceiling(Math.Sqrt(primeTester));
uint i = 2;
while (i <= squareRt)
{
if (primeTester % i == 0)
return false;
i++;
}
return true;
}
There is some noise in the main method, where +/-1 stuff and they are nested the loops. We can use a couple of Linq/IEnumerable features to roll it out and get it on a bit more functional form. It does not matter either to or from the performance, but the intention of the code comes out better for the reader without charge, but some flow control lapses and comments:
Code:
static void Main(string[] args)
{
ulong primeEnter = Convert.ToUInt64(args[0]); // start her, ingen -1 her lenger
ushort numberOfPrimes = Convert.ToUInt16(args[1]);
var primes = NumbersFrom(primeEnter).Where(x => x.IsPrime());
foreach(var prime in primes.Take(numberOfPrimes))
Console.WriteLine(prime);
}
private static IEnumerable<ulong> NumbersFrom(ulong start)
{
while(start <= ulong.MaxValue)
yield return start++;
}
Bookmarks