Kibbee.ca
icon
Project Euler: Problem 4 (revision)

Ever have one of those programming problems when you knew there was a better answer, and you just couldn't solve it right now. I'm a big advocate of stepping away from the computer, or going onto some other problem when you are blocked, and can't figure out the answer you are looking for.

So, here is my revised answer to project euler, problem 4.

largestPalindrome = 0
pi = 0
pj = 0

exitAll = False 
#loop over numbers from 999 to 100 in reverse order
for i in range(999,99,-1):
	#this will get set when we want to exit all
	#loops, when none of the remaining
	#products can possibly be more than the
	#largest palindrome.
	if exitAll: 
		break
	
	#loop from 999 to i 
	#so we don't have to double 
	#check numbers because x * y == y * x
	for j in range(999,i-1,-1):
		product = i * j
		#if the product is less than the largestPalindrome
		#then we show just exit the loop, and move
		#onto the next item in the outer loop
		#if we have only checked the first value of J
		# (999), then we should just exit 
		# altogether, because no other products
		# will be > largest palindrome
		if product < largestPalindrome:
			if j == 999:
				exitAll = True
			     
			break
		
		#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
			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]

the comments explain it all for the most part. Basically I'm counting down from 999 to 0, and the inner loop only goes from 999 to the value of the outer loop. I also break out of the whole thing once I get to a point where I've found a palindrome and no other products can possibly be greater than the current one. It doesn't make much difference in the run time for finding the largest Palindrome of 2, 3 digit numbers, but when I ran it for 6 and 7 digit numbers, it makes a huge difference.

No Comments Posted