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: Running time = 5.29s
+-;binary
(defn binary [n]
(if (= n 0)
"0"
(loop [rem n res ""]
(if (= n 0)
res
(recur
(bit-shift-right n 1)
(str (if (= 1 (bit-and n 1)) "1" "0") res)
)
)
)
)
)
+-;is-palindrome?
(defn is-palindrome? [s]
(let [ss (seq (str s))]
(= ss (reverse ss))
)
)
(defn p36 []
(println
(apply + (filter #(and (is-palindrome? %) (is-palindrome? (binary %))) (range 1 1000000)))
)
)
Erlang: Running time = 0.62s
+-%binary
binary(0)->"0";
binary(N)->binary(N,[]).
binary(0,L)->L;
binary(N,L)->
case N band 1 of
1->
binary(N div 2, lists:append("1",L));
0->
binary(N div 2, lists:append("0",L))
end.
+-%is_palindrome
is_palindrome(N)->
S=integer_to_list(N),
S == lists:reverse(S).
p36()->
p36(1,0).
p36(1000000,Sum)->io:format("~w~n",[Sum]);
p36(N,Sum)->
case is_palindrome(N) of
true->
B=binary(N),
case B==lists:reverse(B) of
true->
p36(N+1,Sum+N);
false->
p36(N+1,Sum)
end;
false->
p36(N+1,Sum)
end.
Ruby: Running time = 2.06s
+-#Enumerable
module Enumerable
def sum
self.inject{|u,v|u+v}
end
def product
self.inject{|u,v|u*v}
end
def count(ob)
self.select{|i|i==ob}.length
end
def take_while
return [] unless yield(self.first)
if(self.class==Range)
evalPoint=self.first
evalPoint=evalPoint.succ while yield(evalPoint.succ) and not evalPoint==self.last
return self.first..evalPoint
else
s=self.to_a
upTo=1
upTo+=1 while yield(s[upTo]) and upTo<self.length
return self[0...upTo]
end
end
end
+-#isPalindrome?
def isPalindrome?(n)
s=n.to_s
s==s.reverse
end
def p36
puts (1..1000000).select{|i|isPalindrome?(i) and isPalindrome?(i.to_s(2))}.sum
end