Project Euler Question 3 Help

后端 未结 16 1324
攒了一身酷
攒了一身酷 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

    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

    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.

提交回复
热议问题