Project Euler Question 3 Help

后端 未结 16 1327
攒了一身酷
攒了一身酷 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 09:10

    You need to reduce the amount of checking you are doing ... think about what numbers you need to test.

    For a better approach read up on the Sieve of Erathosthenes ... it should get you pointed in the right direction.

    0 讨论(0)
  • 2020-12-08 09:10

    As for the reason to accepted nicf's answer:

    It is OK for the problem at Euler, but does not make this an efficient solution in the general case. Why would you try even numbers for factors?

    • If n is even, shift left (divide by 2) until it is not anymore. If it is one then, 2 is the largest prime factor.
    • If n is not even, you do not have to test even numbers.
    • It is true that you can stop at sqrt(n).
    • You only have to test primes for factors. It might be faster to test whether k divides n and then test it for primality though.
    • You can optimize the upper limit on the fly when you find a factor.

    This would lead to some code like this:

    n = abs(number);
    result = 1;
    if (n mod 2 = 0) {
      result = 2;
      while (n mod 2 = 0) n /= 2;
    }
    for(i=3; i<sqrt(n); i+=2) {
      if (n mod i = 0) {
        result = i;
        while (n mod i = 0)  n /= i;
      }
    }
    return max(n,result)
    

    There are some modulo tests that are superflous, as n can never be divided by 6 if all factors 2 and 3 have been removed. You could only allow primes for i.

    Just as an example lets look at the result for 21:

    21 is not even, so we go into the for loop with upper limit sqrt(21) (~4.6). We can then divide 21 by 3, therefore result = 3 and n = 21/3 = 7. We now only have to test up to sqrt(7). which is smaller then 3, so we are done with the for loop. We return the max of n and result, which is n = 7.

    0 讨论(0)
  • 2020-12-08 09:13

    Try using the Miller-Rabin Primality Test to test for a number being prime. That should speed things up considerably.

    0 讨论(0)
  • 2020-12-08 09:13

    Another approach is to get all primes up to n/2 first and then to check if the modulus is 0. An algorithm I use to get all the primes up to n can be found here.

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