简体   繁体   中英

C# find large prime numbers

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.

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.

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.

    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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM