Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Solution
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143?
def PrimeFactor(number)
isPrime = true;
factors = Array.new
factorCandidate = Math.sqrt(number).floor
while factorCandidate > 1 do
if number % factorCandidate == 0 then
isPrime = false;
#kinda like the ‘push’ syntax here
PrimeFactor(factorCandidate).each {|factor| factors << factor }
PrimeFactor(number / factorCandidate).each {|factor| factors << factor }
end
factorCandidate -= 1
end
if isPrime then
factors.Add(number)
end
factors
end
factors = PrimeFactor(600851475143)
puts factors.max
Discussion
Even though I copied and pasted my C# solution here it still took me a while to iron out the kinks. There are some things I really enjoy about the syntax so far, but I still haven’t discovered the virtue of dynamic typing. Maybe I will as time passes.
If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).
Leave a Reply