Project Euler with Ruby on WSL [Problem 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.

私訳

どちらから読んでも同じ数を「回文数」と呼ぶことにする。 3桁の数同士の積で、最大の回文数を求めよ。

解答方針

{100..999} * {100..999} で回文数になるものを探すわけだ。 高々 900*900 = 810000 個なのでごり押しで行けそう。

面倒なので回文数かどうかの判定も文字列にしてひっくり返すことにする

解答

# Project Euler
# problem 4

def palindromic?(num)
    s = num.to_s
    return s == s.reverse
end

def all_palindromic(digits)
    max = 10**digits - 1 # e.g. digits=2 => 10**2-1 => 99
    min = 10**(digits - 1) # e.g. digits=2 => 10**(2-1) => 10
    list = []
    i = max
    while i >= min
        j = i
        while j >= min
            n = i*j
            if(palindromic? n)
                list.push([i, j, n])
            end
            j-=1
        end
        i-=1
    end
    list
end

def largest_palindromic(digits)
    all_palindromic(digits).max{|a,b| a[2] <=> b[2]}
end

pp largest_palindromic(3)