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.)

Sage Solution

This is relatively straightforward in Sage.

import time
def is_palindromic(n):
    d = n.digits()
    if len(d) == 1: return True
    for i in range(floor(len(d)/2)):
        if d[i] != d[len(d)-1-i]: return False
    return True
def is_b_palindromic(n):
    n = ZZ(bin(n).split('0b')[1])
    return is_palindromic(n)
start = time.time()
s = 0
for n in range(1000000):
    if is_palindromic(ZZ(n)) and is_b_palindromic(ZZ(n)): s += n
elapsed = time.time() - start
print "result %s found in %s seconds" % (s, elapsed)

Executing that bit of code, we get the following result.

result 872187 found in 21.3442850113 seconds
Posted in Sage
Share this post, let the world know

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">