Project Euler Question 3 Help

后端 未结 16 1325
攒了一身酷
攒了一身酷 2020-12-08 08:25

I\'m trying to work through Project Euler and I\'m hitting a barrier on problem 03. I have an algorithm that works for smaller numbers, but problem 3 uses a very, very large

相关标签:
16条回答
  • 2020-12-08 08:47

    Easy peasy in C++:

    #include <iostream>
    
    using namespace std;
    
    
    int main()
    {
        unsigned long long int largefactor = 600851475143;
        for(int i = 2;;)
        {
            if (largefactor <= i)
                break;
            if (largefactor % i == 0)
            {
                largefactor = largefactor / i;
            }
            else
                i++;
        }
    
        cout << largefactor << endl;
    
        cin.get();
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-08 08:47

    you might want to see this: Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?

    and I like lill mud's solution:

    require "mathn.rb"
    puts 600851475143.prime_division.last.first

    I checked it here

    0 讨论(0)
  • 2020-12-08 08:51

    Once you find the answer, enter the following in your browser ;)

    http://www.wolframalpha.com/input/?i=FactorInteger(600851475143)

    Wofram Alpha is your friend

    0 讨论(0)
  • 2020-12-08 08:52

    Although the question asks for the largest prime factor, it doesn't necessarily mean you have to find that one first...

    0 讨论(0)
  • 2020-12-08 08:52
    long n = 600851475143L; //not even, so 2 wont be a factor
    int factor = 3; 
    while( n > 1)
    {
        if(n % factor == 0)
        {
            n/=factor;
        }else
            factor += 2; //skip even numbrs
    }
            print factor;
    

    This should be quick enough...Notice, there's no need to check for prime...

    0 讨论(0)
  • 2020-12-08 08:55

    The way I did it was to search for primes (p), starting at 2 using the Sieve of Eratosthenes. This algorithm can find all the primes under 10 million in <2s on a decently fast machine.

    For every prime you find, test divide it into the number you are testing against untill you can't do integer division anymore. (ie. check n % p == 0 and if true, then divide.)

    Once n = 1, you're done. The last value of n that successfully divided is your answer. On a sidenote, you've also found all the prime factors of n on the way.

    PS: As been noted before, you only need to search for primes between 2 <= n <= sqrt(p). This makes the Sieve of Eratosthenes a very fast and easy to implement algorithm for our purposes.

    0 讨论(0)
提交回复
热议问题