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!
- success = 0
- for i in (100..999)
- for j in (100..999)
- k = i * j
- if (k.to_s == k.to_s.reverse && k > success)
- success = k
- end
- end
- end
- 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