Project Euler 3 - Highest Prime Factor

前端 未结 2 1047
-上瘾入骨i
-上瘾入骨i 2021-01-28 03:52

before I start I want to clarify that I am not looking for code examples to get the answer; that would defeat the object of Project Euler.

The problem

2条回答
  •  悲&欢浪女
    2021-01-28 04:31

    If you start div at 2 and count up instead of down, and divide it out from the number when the modulo is zero, you gain two big advantages that are useful here:

    1. You don't have to check if div is prime, since it can't be composite because any prime factors smaller than it would already have been divided out.
    2. You reduce the remaining problem size every time you find a factor, and, as it turns out, the input number has fairly small prime factors.

    You could then also break once div*div is greater than the remaining number, as you know at that point that it must be a prime. This is because any divisors greater than the square root are "paired" with one less than the square root. However, since this is an "easy" problem, this optimization is not needed here (although it is useful for later problems).

提交回复
热议问题