Project Euler – Problem 3

This is the third post in my Project Euler series (if series is the right word). The second problem is here.

Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

This problem seemed rather daunting to me at first. Upon first reading it, I thought to myself ‘I know I’ve learned about prime factors before.’ But unfortunately, somewhere along the lines of learning calculus, linear algebra, and discrete math I forgot about those little prime factor thingys.

So, with a little help from Math is Fun and the ever-present ruler of knowledge Wikipedia, I quickly remembered what prime factors are.

Firstly, what is a factor? When you multiply numbers together, those numbers are called factors. For example (image supplied from Math is Fun):

factor-2x3

Simple enough. So a prime factor, obviously, is a factor that is prime. The easiest way to calculate all of the prime factors of a number is divide out all of the 2’s, then the 3’s, and so on. Here’s an example of finding the prime factors of 12.

The way this works is quite simple. By dividing out all of the 2’s, we know that we have divided out all of the multiples of 2. If we divided out 4 before 2, then we would be left with a non-prime factor. But by dividing all of the 2’s out of x, we’ll be left with some x’ that is not divisible by any multiples of 2.

This simple, albeit non-efficient method allows us to write an answer quite easily.

Here’s the generic answer, complete with a few optimizations (for example, skipping all multiples of 2). I chose to use longs instead of ints just to make the answer slightly more generic.

 

Leave a Reply

Your email address will not be published. Required fields are marked *