## Project Euler Problem 3

### September 20, 2011

Problem 3 at Project Euler asks the reader to solve this problem:

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?

Given the amount of factoring code on this website, I find that problem quite simple. But judging from Reddit and Stack Overflow, other programmers find the problem anything but simple. If you look at the dates, you will notice that the problem seems to come up every few months. And if you read the comments on Reddit and Stack Overflow, the saddest part is that a lot of the answers are wrong; in fact, some of them are mind-numbingly wrong. So I decided to write a canonical solution to the problem:

Project Euler Problem 3 asks for the largest prime factor of the number 600851475143. We consider first a function to find all the prime factors of any number. A simple way, not necessarily the best way but sufficient for this task and for many others, works in two steps: first remove factors of 2 while the number is even, then perform trial division by the odd numbers starting from 3 until the factorization is complete. Here’s a formal statement of the algorithm to find the factors of a given input number

n:1. Create a list of factors, initially empty.

2. If

nis even, add 2 to the end of the list of factors, dividenby 2, and go to Step 2.3. Set

f← 3.4. Calculate the quotient

qand remainderrwhen dividingnbyf, so thatn=q f+rwith 0 ≤r<f.5. If

r> 0, setf←f+ 2 and go to Step 4.6. Otherwise,

r= 0. Addfto the end of the list of factors. Setn←q.7. If

n<f^{2}, addnto the end of the list of factors, output the list of factors, and stop.8. Otherwise, go to Step 4.

Consider as an example the factorization of 13195; it’s odd, so we pass Step 2 and go to Step 3 with

f= 3. The quotient and remainder of 13195 ÷ 3 are 4398 and 1, so in Step 5 we setf= 3 + 2 = 5 and go to Step 4. The quotient and remainder of 13195 ÷ 5 are 2639 and 0, so in Step 6 we add 5 to the end of the list of factors, making the list {5}, and we setn= 2639. Then, in Step 7, we note that 2639 < 5^{2}is false, so we go to Step 8 and then to Step 4. In Step 4 we calculate the quotient and remainder of 2639 ÷ 5 as 527 and 4, and since the remainder is greater than 0 we setf= 5 + 2 = 7 and go to Step 4. In Step 4 we calculate the quotient and remainder of 2639 ÷ 7 as 377 and 0, so in Step 6 we add 7 to the end of the list of factors, making the list {5, 7}, and we setn= 377. Then, in Step 7, we note that 377 < 7^{2}is false, so we go to Step 8 and then to Step 4. In Step 4 we calcuate the quotient and remainder of 377 ÷ 7 as 53 and 6, and since the remainder is greater than 0 we setf= 7 + 2 = 9 and go to Step 4. In Step 4 we calculate the quotient and remainder of 377 ÷ 9 as 41 and 8, and since the remainder is greater than 0 we setf= 9 + 2 = 11 and go to Step 4. In Step 4 we calculate the quotient and remainder of 377 ÷ 11 as 34 and 3, and since the remainder is greater than 0 we setf= 11 + 2 = 13 and go to Step 4. In Step 4 we calculate the quotient and remainder of 377 ÷ 13 as 29 and 0, so in Step 6 we add 13 to the end of the list of factors, making the list {5, 7, 13}, and we setn= 29. Then, in Step 7, we note 29 < 13^{2}, so we add 29 to the end of the list of factors, making the list {5, 7, 13, 29}, output the list of factors, and stop. Thus, the complete factorization is 13195 = 5 × 7 × 13 × 29.Given a function to find the prime factors of a number, the solution to Project Euler Problem 3 is easy: it’s just the last prime factor in the list, which is necessarily the largest prime factor in the list since we worked with increasing

fand always added prime factors to the end of the list.You may notice that the challenge number in the problem, 600851475143, is too large to represent using 32-bit arithmetic. That’s part of the Project Euler task — you need to find a library that allows you to do arithmetic on numbers longer than 32 bits. In fact, Project Euler uses this problem as kind of a gateway exercise, because many of the later problems also require arithmetic on integers longer than 32 bits. With C, the long long datatype is big enough, but you might need the gmp library for larger integers, with Java you probably want the BigInteger library, and with other languages you will need to find the corresponding library yourself, and let the compiler know where it is so it can be linked to your factoring code. Or you may prefer to use a language, such as Python or Lisp, that provides built-in support for integers longer than 32 bits.

If you want to know more about integer factorization, I humbly recommend the prime-number exercises at my blog.

Your task is to implement the function described above. If you solve the Project Euler problem, please publish only your code but not the solution, as we respect Project Euler’s request not to publish answers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

It looks like this may not behave well for powers of two, though it handles other evens fine:

Python:

Huzzah for native big integers!

How embarrassing! I need a step 2.5 that reads “If

n= 1, output the list of factors and stop.” and make the corresponding change in the function.Trying to learn Google Go, first time using big.Int

Have to say that I don’t find it very intuitive to use, but then again, I’m only just starting..

Oh, sorry for the cruft.. used an online syntax highlighter, but doesn’t appear that it worked very well.

In ruby (pretty much exactly the same as Graham’s python version) …

You could also monkey patch Integer to provide this in a more ruby like way.

In Python. Slightly more verbose, and with the steps interspersed through the code as comments. I’m gradually getting the hang of Python.

Source

Same problem solved in C# language

https://sites.google.com/site/eulerproblemsincsharp/home/problem-3

Here’s a slight twist on the described function. Rather than try all

odd numbers >= 3, I used a 30-wheel to generate the possible factors.

Also, the function is a generator which returns successive factors of its

argument. Use list() to get the last factor.

@graham/@slabounty – I think line 12/14 should be f += 2, so that f skips even numbers.

Thanks for catching that, @Mike; I could have sworn I put in += 2. Anyway, nice wheel! I’ll have to read up on wheel factorization and Python3′s accumulate.

Graham, you can read about wheel factorization at the earlier exercise at Programming Praxis.

C# version

in c language

#include

int main()

{

long long int n = 600851475143;

long long int a[100];

long long int i,f,q,r,j;

i=0;

while(n%2==0)

{

a[i] = 2;

i++;

n=n/2;

}

f=3;

while(n > (f*f))

{

q = n/f;

r = n%f;

if(r>0)

{

f = f+2;

}

else

{

a[i] = f;

i++;

n = q;

if(n < (f*f))

{

a[i] = n;

i++;

}

}

}

for(j=0; j<i; ++j)

printf("%lld ",a[j]);

printf("\n");

return 0;

}

FORTH Version to find greatest prime factor. Rather than factor all even numbers, the first step factors all even numbers > 2. When n is equal to 2, the square test fails, so the odd factoring loop does not execute. Therefore there is no special case to check for n = 1 at the end, but more importantly the invariant is preserved that when the function ends, the greatest prime factor is on the stack as a 64 bit integer. (If the final “d.” and printing is removed, the FORTH word would become a function to return the largest prime factor.)

Testing:

C#:

long num = 600851475143;

long f = 1;

long z = 1;

while (z != num)

{

if (num % f == 0)

{

Console.WriteLine(f);

z = z * f;

}

f++;

}

Console.WriteLine(“DONE!”);

Console.ReadLine();

In Java:

public class LargestPrimeFactor {

private static double primefactor(double n) {

double i=2;

for(;itemp)? i:temp;

}

}

return i;

}

public static void main(String[] args) {

System.out.println(primefactor(600851475143.0));

}

}

HMM the above code was cut off

public class LargestPrimeFactor {

private static double primefactor(double n) {

double i=2;

for(;itemp)? i:temp;

}

}

return i;

}

public static void main(String[] args) {

System.out.println(primefactor(600851475143.0));

}

}