Question
The decimal number, 585 = 1001001001_2 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
Clojure
#!/usr/bin/env clojuredefn reversed [string]
(apply str (reverse string)))
(
defn palindrome? [string]
(= string (reversed string)))
(
defn palindrome-in-decimal-and-binary? [n]
(and (palindrome? (Integer/toString n 2))
(
(palindrome? (Integer/toString n))))
println (reduce + (filter palindrome-in-decimal-and-binary? (range 1 1000000)))) (
$ time clojure palindromic-bases.clj
real 0m3.059s
user 0m4.238s
sys 0m0.270s
Haskell
palindrome :: Eq a => [a] -> Bool
= s == reverse s
palindrome s
digits :: Int -> Int -> [Int]
0 = []
digits _ = r : digits base q
digits base n where (q, r) = quotRem n base
main :: IO ()
= print $ sum [n | n <- [1..1000000], all palindrome [digits 10 n, digits 2 n]] main
$ ghc -O2 -o double-palindrome double-palindrome.hs
$ time ./double-palindrome
real 0m0.150s
user 0m0.142s
sys 0m0.008s
Ruby
#!/usr/bin/env ruby
class String
def palindrome?
self == self.reverse
end
end
puts (1..1000000).select { |i| i.to_s.palindrome? && i.to_s(2).palindrome? }.reduce(:+)
$ time ruby binary-palindrome.rb
real 0m0.365s
user 0m0.365s
sys 0m0.000s