Skip to content

Instantly share code, notes, and snippets.

@jtallant
Created July 7, 2012 05:31
Show Gist options
  • Save jtallant/3064908 to your computer and use it in GitHub Desktop.
Save jtallant/3064908 to your computer and use it in GitHub Desktop.
Project Euler Problem 4 Ruby
# 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