004 Largest palindrome product.sf 714 B

123456789101112131415161718192021222324252627282930
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 09 October 2017
  4. # https://github.com/trizen
  5. # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  6. # Find the largest palindrome made from the product of two 3-digit numbers.
  7. # https://projecteuler.net/problem=4
  8. # Runtime: 0.175s
  9. func largest_palindrome_product (n) {
  10. for k in ((10**n - 1) `downto` 10**(n-1)) {
  11. var t = Num("#{k}#{Str(k).flip}")
  12. t.divisors.each {|d|
  13. if ((d.len == n) && ((t/d).len == n)) {
  14. return [d, t/d, t]
  15. }
  16. }
  17. }
  18. }
  19. say largest_palindrome_product(2)
  20. say largest_palindrome_product(3)