Analysis

Before reading through this section, I encourage you to think of a possible solution of your own first ~🎀

“Largest prime factor” let’s break it down and agree on some definitions first, before analysing this puzzle:

Factor: If a divides N evenly, i.e. without a remainder, then a is a factor of N. For example, 3 is a factor of 9.

Prime: A number is Prime if it has no factors except one and itself. In english, a prime number can only be divided evenly (no reminder) by 1 and itself.

8 isn’t prime because it can be divided by 2. On the other hand, 7 is a prime number because the only numbers that divide seven evenly are 7 and 1.

Large: Well this need no definition.

Following the previous definitions, one way to solve this problem is to generate a list of all prime numbers less than our boundary 10¹², Then iterate over it to find the largest prime that could divide our given N.

But that’s a pretty naive solution.

Prime factorisation

One efficient way to solve Project Euler 3, is to prime factorise the number and get the maximum factor.

which is basically the same as the naive solution above but with a better mathematical approach. resulting on more efficiency.

With a boundary of 10¹², a refined Eratosthenes sieve would solve the problem in a fairly acceptable time.

Here’s my commented implementation in Python:

Python implementation of Max prime factor using a refined sieve.

Pollard’s rho algorithm

Now that we came to the conclusion that this problem can be solved by any prime factorisation algorithm. The door opens up to many fun and interesting algorithms.

For all the number theory nerds out there, I recommend looking at this question thread on Quora where people discuss fancy prime factorisation algorithm.

Meanwhile here’s my modest solution of ProjectEuler3 using the Pollard’s rho algorithm:

Python implementation of Max prime factor using Pollard’s rho algorithm.

If you are interested in an easy explanation and simple walkthrough of the Pollard's rho algorithm, leave me a message, and I’ll try to write down a separate article about it. Meanwhile make sure to follow me on medium for more awesome Project Euler editorials.