简体   繁体   中英

Why does my program for finding the largest prime never writes to console?

I debugged my code and everything works perfectly. But my code never writes to console for some reason.

Here is my code:

  long largest = 0;


        for (long i = 1; i < 600851475144; i++)
        {
            long check = 0;
            for (long j = 1; j < i + 1; j++)
            {

                if ((i%j) == 0)
                {
                    check++;
                }
            }
            if (check == 2)
            {
                largest = i;
            }
        }

        Console.WriteLine(largest);
        Console.ReadKey();

Question: How do I write to console?

What?

It will finish, but it will last forever because of all the iterations it has to do.

Prime finding calculation is a very intensive calculation, specially in the way you have done it.

Summarizing, it does not return because you have to wait minutes/hours/days/years? To compute that.

Your algorithm is too slow to complete in a reasonable time, so you need to come up with an alternative approach.

First, the algorithm has to stop checking the naive definition (two divisors). If you check all divisors up to square root of the number, and did not find any, the number is prime. Second, if you are looking for the largest prime in a range, start at the top of the range, go down, and stop as soon as you find the first prime. Third, there is no point to try even numbers.

Implementing these three changes will get your algorithm running in time.

Your algorithm is poor. It has to make a lot of iterations. As others have already mentioned, there is no sense to divide by even numbers thus incremen by two, start with 3, you can reduce the iteration count to the square root of given number. mine is not perfect as well but it finishes in a blink. The idea is to reduce count of iterations by dividing the given number by all found divisors. Try at your own risk!

    long FindLargestPrimeDivisor(long number)
    {
        long largestPrimeDivisor = 1;
        while (true)
        {
            if (number % largestPrimeDivisor == 0)
            {
                number /= largestPrimeDivisor;
            }
            if (number < largestPrimeDivisor)
            {
                break;
            }
            largestPrimeDivisor++;
        }
        return largestPrimeDivisor;
    }

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