project_euler/3.rb
Code:
# Project Euler Problem 3: Largest Prime Factor
# https://projecteuler.net/problem=3
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143?
def prime_factors(n)
(2...n).each do |factor|
if (n % factor == 0)
other_factor = n / factor
return [*prime_factors(factor), *prime_factors(other_factor)]
end
end
return [n]
end
puts prime_factors(13195).max
puts prime_factors(600851475143).max
Output:
29
6857