Created
July 7, 2012 05:31
-
-
Save jtallant/3064908 to your computer and use it in GitHub Desktop.
Project Euler Problem 4 Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. | |
# Find the largest palindrome made from the product of two 3-digit numbers. | |
def looped_palindrome(num1,num2=num1) | |
product = 0 | |
while num1 > 900 | |
product = num1 * num2 | |
return product if product.to_s == product.to_s.reverse | |
if num2 > 900 | |
num2 -= 1 | |
else | |
num1 -= 1 | |
num2 = num1 # avoids multiplying same numbers again | |
end | |
end | |
end | |
puts looped_palindrome(999) # => 906609 | |
def recursive_palindrome(num1,num2=num1) | |
product = num1 * num2 | |
return product if product.to_s == product.to_s.reverse | |
if num2 > 900 | |
num2 -= 1 | |
else | |
num1 -= 1 | |
num2 = num1 # avoids multiplying same numbers again | |
end | |
recursive_palindrome(num1, num2) | |
end | |
puts recursive_palindrome(999) # => 906609 | |
def time | |
start = Time.now | |
yield | |
puts Time.now - start | |
end | |
time { looped_palindrome(999) } | |
time { recursive_palindrome(999) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment