Friday, February 06, 2009

Project Euler - Problem 3

Problem 3 reads as follows:

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

What is the largest prime factor of the number 600851475143 ?"


This one is easy, thanks to Ruby's mathn library and the prime_division method. You can read more about it and even see the source code for the method at the documentation site.

All we have to do is require the mathn library, which comes with Ruby by default. I checked on my Windows and Mac OSX machines. Then call the prime_division method on the integer. That creates a multidimensional array.

For each item in the array, there are 2 numbers. The first is the actual prime number and the second relates how many times that prime number can be factored out. So, for the number 9, you would end up with [3,2].

Lastly, we grab the last prime number in the array for the answer.

require 'mathn'
primeArray = 600851475143.prime_division
puts primeArray[primeArray.length - 1][0]

2 comments:

Anonymous said...

Genial brief and this fill someone in on helped me alot in my college assignement. Thank you seeking your information.

Anonymous said...

Nice post and this mail helped me alot in my college assignement. Thanks you as your information.