Kibbee.ca
icon
Project Euler: Problem 4

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

[Full Question]

largestPalindrome = 0
pi = 0
pj = 0

#loop over all 3 digit numbers to 
# find the largest palindrome
for i in range(100,1000):
	for j in range(100,1000):
		product = i * j
		#convert the product to a string
		sprod = "%d" % (product,)
		#check if the product is the same 
		#forwards as backwards
		if sprod == sprod[::-1]:
			#if it's a palendrome
			#and larger the largest,
			#we set it to the largest
			if product > largestPalindrome:
				largestPalindrome = product
				pi = i 
				pj = j

print "The largest palendrome is %d" % (largestPalindrome,)
print "it is the product of %d and %d" % (pi,pj)

[Download Code]

A very basic brute force way of finding the largest palendrome. Tried some other methods, such as counting down from the top, and stopping at the first palendrome found, but this failed to find the largest palendrome, because the largest palendrome was the product of one large number, and a one smaller number, which wouldn't be found first in any way of looking.

No Comments Posted