Skip to content

Instantly share code, notes, and snippets.

@jgilless

jgilless/euler3.rb

Created Nov 14, 2014
Embed
What would you like to do?
Ruby solution for Project Euler problem 3
# https://projecteuler.net/problem=3
puts "Find the largest prime factor of:"
STDOUT.flush #clears the buffer
max_num = Integer(gets.chomp)
def largest_prime_factor(num)
largest_factor = 1
#get rid of factors of 2
while num % 2 == 0
largest_factor = 2
num /= 2
end
#get rid of odd factors starting at the bottom and moving up from 3
odd = 3
while num != 1
#look at the condition where the number is divisible by the odd number on deck
while num % odd == 0
largest_factor = odd
num /= odd
end
odd += 2
end
largest_factor #return
end
puts "Largest prime factor of #{max_num} = " + largest_prime_factor(max_num).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment