Reputation: 579
I'm writing a program in C# that will find all the prime numbers up to the max size of UInt64, unless there's a numerical data type larger than UInt64. I've already written the simple program but for some reason, it's returning every single number I check as a prime even if they're not supposed to be a prime number. Here's what I have:
static void Main(string[] args)
{
UInt64 count = 0;
List<UInt64> primes = new List<UInt64>();
bool prime = true;
do
{
for (UInt64 i = 2; i < count; i++)
{
if ((count % i) == 0)
{
prime = false;
}
}
if (prime == true)
{
primes.Add(count);
Console.WriteLine(count);
}
count++;
prime = true;
} while (count < UInt64.MaxValue);
}
Is there something wrong with my algorithm. Because every time I do the check for a prime, it thinks every number is a prime and will print it out.
Upvotes: 0
Views: 1645
Reputation: 121
IEnumerable<UInt64> PrimeNumbers(UInt64 maxCap = UInt64.MaxValue)
{
yield return 2;
yield return 3;
for (var i = 4; i <= maxCap; i++)
{
var isPrime = true;
for (var j = 2; j <= i / 2; j++)
{
if (i % j != 0) continue;
isPrime = false;
break;
}
if (isPrime) yield return i;
}
}
Upvotes: 0
Reputation: 1797
Well first of all, 0 and 1 is not prime and it is a very slow algorithm. You shoould consider some optimaze the code. Like this But your code should work fine.
Upvotes: 0
Reputation: 32309
I literally copy-pasted your code into Visual Studio, ran it and it worked perfectly. The algorithm is sound, although you could definitely optimize it.
Upvotes: 2