Thursday, August 11, 2011

Project Euler #4 in Ruby

Project Euler #4

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.

Another great example here! 


  1. success = 0
  2. for i in (100..999)
  3.   for j in (100..999)
  4.     k = i * j
  5.     if (k.to_s == k.to_s.reverse && k > success)
  6.       success = k
  7.     end
  8.   end
  9. end
  10. puts success

What happens here is very straightforward, because he is asking for two, three-digit numbers multiplied together, it immediately tells us the constraints of our two for loops, and thereby the maximum possible value we could have:  999x999 or 998001.  What we need to do then is just compare the value we get from multiplying them together, and then the reverse of that, thereby checking to see if it is palindromic.  It's super easy in Ruby as well, you just have to convert both to strings using the '.to_s' operator and then the '.reverse' on one of them.  In line 5 the first conditional 'k.to_s == k.to_s.reverse' checks to see if it is palindromic and the second if it is greater than the last palindrome that we found, because there will be many.  If it is, the line 6 states that we save it. 

This code runs in just over a second for me, satisfying the 1 minute guideline set forth by the project Euler team. 

No comments:

Post a Comment