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.
Clojure: Running time = 6.04s
+-;cartesian-product
(defn cartesian-product [& lists]
(if (= 1 (count lists))
(map list (first lists))
(let [recurs (apply cartesian-product (rest lists))]
(apply concat (map (fn [el] (map #(cons el %) recurs)) (first lists)))
)
)
)
+-;is-palindrome?
(defn is-palindrome? [s]
(let [ss (seq (str s))]
(= ss (reverse ss))
)
)
(defn p4 []
(println
(apply max (filter is-palindrome? (map (fn [[a b]] (* a b)) (cartesian-product (range 100 1000) (range 100 1000)))))
)
)
Erlang: Running time = 0.52s
+-%is_palindrome
is_palindrome(N)->
S=integer_to_list(N),
S == lists:reverse(S).
p4()->
Candidates=lists:append(lists:map(fun(Top)->
lists:map(fun(T)->T*Top end,
lists:seq(100,Top-1))
end,lists:seq(101,999))),
Ans=lists:last(lists:sort(lists:filter(fun(X)->is_palindrome(X) end,Candidates))),
io:format("~w~n",[Ans]).
Ruby: Running time = 3.64s
+-#cartesian_product
def cartesian_product(*a)
return [] if a.length==0
return a[0].map{|h|[h]} if a.length==1
a.map!{|b| b.to_a}
b=cartesian_product(*(a[1..-1]))
a=a[0]
res=[]
if block_given?
a.each do |aitem|
res=res+b.select{|i|yield(aitem,*i)}.map{|i|[aitem]+i}
end
else
a.each do |aitem|
b.each{|bitem| res.push([aitem]+bitem)}
end
end
res
end
+-#isPalindrome?
def isPalindrome?(n)
s=n.to_s
s==s.reverse
end
def p4
puts cartesian_product((100...1000),(100...1000)).map{|p|p[0]*p[1]}.select{|i|isPalindrome? i}.sort[-1]
end
Scala: Running time = 1.35s
+-//isPalindrome
def isPalindrome(n: BigInt)={
val s=n.toString
s==s.reverse.toString
}
def p4{
var l=0
for(i <- (100 until 1000); j<- (100 until 1000) if isPalindrome(i*j))if(i*j>l)l=i*j
println(l)
}