Pete On Software

RSS Feed

Project Euler Problem Three

Optimus PrimeIt has been almost two years since I tackled Project Euler Problems One and Two. I really wanted to get back into it, so there really is no time like the present to do the work. I’m on my Mac Mini right now, so I developed this in C#.Net using MonoDevelop.

This problem needs us to find the largest prime factor of a very large number. Obviously, to do this, you need to be able to generate a set of prime numbers to work with. I have an IsPrime method that uses a very brute force method (with the shortcut of only checking as high as the square root of the number). I Googled around for ways to generate primes and looked into the Sieve of Eratosthenes, but it was a little complicated for the time I had allotted myself to work on this problem (basically the ten minutes until I had to put my son to bed). Plus, it turns out that this entire piece of code runs in under a second on my several year old Mac Mini, so there was no need to optimize yet. I know that later Project Euler problems also deal in primes, so I may need to break it out then.

Once I had that method in place, it was really a simple matter of working up to the square root of the number in the problem, 600851475143, using the same shortcut. If the number in my loop was prime and evenly divided into our number, I stored it as the current largest number. When I was done, whatever number was currently in that variable was our champion. Pretty simple logic.


Have you attempted this problem yet? What is your solution? I’d love to see them. You can post it in the comments or post a link if you’ve blogged it already.

One Comment

mgroves  on October 10th, 2010

I used a recursive approach. Find the lowest number that divides evenly in the given number. Until those numbers are the same, perform the same check on the number divided by the the lowest even divisor.

Here’s the code, that I think I reused in a later Euler problem: http://mgrovesprojecteuler.codeplex.com/SourceControl/changeset/view/55854#807441