Project Euler Problem 36

Double-base palindromes

The decimal number, 585 = 1001001001 (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.)

Link to original description
Source code examples on Github

Erlang version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p36
% vim:syn=erlang

-mode(compile).

main(_) ->
    Answer = lists:sum([X||X<-lists:seq(1,999999), isDPalindrome(X)]),
    io:format("Answer ~p ~n", [ Answer ]).

isDPalindrome(X) ->
    L = integer_to_list(X),
    case L == lists:reverse(L) of
        true ->
            B = integer_to_list(X,2),
            B == lists:reverse(B)
        ;_   -> false
    end.


Python version 1

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python

def ispalindrome(n):
    s = str(n)
    if s == s[::-1]:
        b = bin(n)[2::]
        return b == b[::-1]
    else:
        return False

print sum(n for n in xrange(1, 1000000) if ispalindrome(n))

Python version 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python

def ispalindrome(n, base):
    digits = []
    reverse = []
    while n > 0:
        d = str(n % base)
        digits.append(d)
        reverse.insert(0, d)
        n = n / base
    return digits == reverse

print sum(n for n in xrange(1, 1000000) if ispalindrome(n, 10) and ispalindrome(n, 2))