Home > ProjectEuler.Net, Python > Project Euler – Problem 4

Project Euler – Problem 4


Homepagehttp://projecteuler.net/problem=4

Problem:

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.

How I solve:
– To solve this puzzle, the most simple method is to cut the number into two equal half-size blocks (if odd, remove the middle digit), then compare one half with the reversed of the other half.

– This is my solution in Python:




def isPalindrome(n):
	size = len(str(n))
	if size % 2 == 0:
		first = str(n)[:size / 2 : ]
		second = str(n)[size / 2 : : 1]
		if first == second[::-1]:
			return True
		else:
			return False
	else:
		first = str(n)[:size / 2 : ]
		second = str(n)[size / 2 + 1: : 1]
		if first == second[::-1]:
			return True
		else:
			return False

def getAllPairsPalindrome():	
	return [ (x, y) for x in xrange(999, 100, -1) for y in xrange(999, 100, -1) if isPalindrome(x * y) == True]
	
def getMaxPairPalindrome():
	max = 0
	pair = []
	for i in getAllPairsPalindrome():
		if i[0] * i[1] > max:
			max = i[0] * i[1]
			pair = [i[0], i[1], i[0] * i[1]]

	return pair
	

# get max pair of 3-digit of palindrome
# [993, 913, 906609]
print getMaxPairPalindrome()

Cheers,
Pete Houston

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: