**Wording:** (Original) The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

**Solution:**

First the code:

[ruby]

include Math

def prime_factors(num, factor=2)

return [] if num <= 1
next_pf = (factor..(sqrt(num).ceil)).find(lambda {num}){ |x| num%x == 0 }
return [next_pf] + prime_factors(num/next_pf, next_pf)
end
puts prime_factors(600851475143).max
[/ruby]
The code is a direct port from the one in PyEuler. It is based mainly in the idea that the first factor of a number is always prime.
Line 3 breaks recursion and line 4 works out the next prime factor (actually, it finds the smallest factor). For doing this, it uses find method. If no element match the criteria, then it returns the number (that is what the lambda block is for).
Finally, line 5 merges the results and line 8 print the result.
This time just one code is showed.

## Author: Serabe

Mathematician, and Ruby and JavaScript programmer.
Sometimes I speak at conferences and local meetups.
View all posts by Serabe