/* Euler #36 in Picat. Problem 36 """ 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.) """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ main => go. go => time(euler36). % , time(euler36a), time(euler36b), time(euler36c). % 0.528s euler36 => println(sum([N : N in 1..999999, is_palindromic(N), Bin = to_radix_string(N,2), Bin == Bin.reverse()])). % 0.554s euler36a => Res = 0, foreach(N in 1..999999) if is_palindromic(N) then Bin = dec_to_base(N, 2), if Bin == Bin.reverse() then Res := Res + N end end end, println(Res). % 0.54s euler36b => println(sum([N : N in 1..999999, is_palindromic(N), is_palindromic(N.to_binary_string())])). % 0.552 euler36c => println(sum([N : N in 1..999999, is_palindromic(N), is_palindromic(dec_to_base(N,2))])). % test binary first is much slower: 4.996s euler36d => println(sum([N : N in 1..999999, is_palindromic(dec_to_base(N,2)), is_palindromic(N) ])). % 1.76s euler36e => println(sum([N : N in 1..999999, is_palindromic(N.to_radix_string(10)), is_palindromic(N.to_radix_string(2)) ])). % for integers is_palindromic(A), integer(A) => A.to_string().is_palindromic(). % for lists is_palindromic(A), list(A) => A == A.reverse(). % % convert a decimal number to base base (as a list) % dec_to_base(N, Base) = reverse(Res) => Res = [], while (N > 0) R := N mod Base, N := N div Base, Res := Res ++ [R] end. dec_to_base2(N, Base) = Conv => Res = [], while (N > 0) R := N mod Base, N := N div Base, Res := [R|Res] end, Conv = Res. dec_to_base3(N, Base) = Res => Res = [], while (N > 0) R := N mod Base, N := N div Base, Res := [R] ++ Res end. dec_to_bin(N) = N.to_binary_string().