简体   繁体   中英

Is my program taking too much time to execute?

I wanted to solve a question from project euleur about finding the largest prime number of a big number. I run my code on a virtual machine on Visual studio 2012, and the code seems froze. When I step into the loop, the code works well, but when I execute it, the console is always there. It is as if the program is still running. Could it be that the program takes time to execute?

My Code

static void Main(string[] args)
{
    long number = 5;

    for (long i = 1; i < 600851475143; i++)
    {
        if (i % 2 != 0 && i % 1 == 0 && i % i == 0)
            number = i;
    }

}

I ran this bit of code and it does take a while to run, but it does seem to progress (i does increment). Try this to determine whether i is a prime:

    public static bool IsPrime(long candidate)
    {
        // Test whether the parameter is a prime number.
        if ((candidate & 1) == 0)
        {
            return candidate == 2;
        }
        // Note:
        // ... This version was changed to test the square.
        // ... Original version tested against the square root.
        // ... Also we exclude 1 at the very end.
        for (int i = 3; (i * i) <= candidate; i += 2)
        {
            if ((candidate % i) == 0)
            {
                return false;
            }
        }
        return candidate != 1;
    }

I can't claim credit for this. It is from http://www.dotnetperls.com/prime .

Add some Console.WriteLines to your main method to its progress:

    static void Main(string[] args)
    {
        long number = 5;

        for (long i = 1; i < 600851475143; i++)
        {
            if (IsPrime(i))
            {
                Console.WriteLine(i);
                number = i;
            }
        }
    }

There's other resources out there for these algorithms too: http://csharpinoneroom.blogspot.com/2008/03/find-prime-numer-at-fastest-speed.html

Good luck!

Your algorithm is incorrect. Here is a simple way to find the prime factors of a composite number, suitable for Project Euler:

function factors(n)
    f := 2
    while f * f <= n
        if n % f == 0
            output f
            n := n / f
        else
            f := f + 1
    output n

This works by dividing n by each f in succession, reducing n and outputting f whenever a prime factor is found. The final factor is the remaining n when f is greater than the square root of n , at which point n must be prime.

There are other ways to factor integers. When you are ready for more, I modestly recommend this essay at my blog.

Ultimately, it doesn't matter if you write the fastest code in the world if it doesn't work correctly. Yours doesn't, speed aside.

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