Posts Tagged ‘palindrome’

Problem 36

Thursday, February 5th, 2009

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

Python just makes these too easy.

?View Code PYTHON
def is_palindrome(x):
  """
  Returns true if the digits of x are the same both backward
  and forward in both base 2 and base 10.
  """
  x10 = str(x)
  x2 = bin(x)[2:]
  return x10 == x10[::-1] and x2 == x2[::-1]
 
# check only odd numbers since even base 2 numbers end in 0
>>> sum(filter(is_palindrome, range(1,1000000,2)))
872187

Problem 4

Tuesday, February 3rd, 2009

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

?View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
def is_palindrome(x):
	x = str(x)
	return x == x[::-1]
 
>>> ans = 0
for x in range(100,1000):
  for y in range(x,1000):
    prod = x*y
    if is_palindrome(prod):
      ans = max([prod,ans])
>>> ans
906609