Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Double-base palindromes : Problem 36 Euler Project

Sunday, September 7, 2014

Double-base palindromes : Problem 36 Euler Project

Double-base palindromes: Problem 36

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

Problem Source : Euler Project

Python Code

def doubleBasePalindromes():
    def reverse(text):
            if len(text) <= 1:
                return text
            return reverse(text[1:]) + text[0]
    def toBinary(numb):
        S = ""
        while numb > 0:
            rem = numb%2
            S = S+str(rem)
            numb = numb/2
        if S == reverse(S):
            return True
        else:       
            return False
    i = 1
    totalSum = 0
    while i <= 1000000:
        if str(i) == reverse(str(i)):
            if toBinary(i) == True:
                totalSum = totalSum + i    
        i = i+1           
    print "Required Sum:",totalSum   
doubleBasePalindromes()       

No comments:

Post a Comment