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.
#!/usr/bin/env python def ispal(num): #Check if the number is a palindrome val = str(num) #Python just does the right thing here. Nice. for each in range(0,int((len(val)+1)/2)): #Any mismatch return false if val[len(val)-1-each]!=val[0+each]: return False return True #otherwise return true def calc(): #brute force looking for palindromes temp = 0 largest = 0 for each in range(999,100,-1): for other in range(999,100,-1): temp = each * other if ispal(temp): largest = max(largest,temp) return largest if __name__ == '__main__' : print (calc())
The answer is 906609.
ApproachThis was one of the problems which took almost no time to code. The seamless casting in Python made this one trivial. You just work from both ends and look for mismatches.
Converting to a string worked exactly like it should have and python made it trivial to code. Using some sort of built-in to reverse the string and see if it matches the original sting would probably be faster than a char by char comparison.
BenchmarksThe benchmarks fell out pretty much like the others. Boring example, Sorry!
Problem #4 Benchmarks
time python palindromes.py
time python -O palindromes.py
time python3 palindromes.py
time python3 -O palindromes.py
time pypy palindromes.py
time pypy -O palindromes.py
time jython palindromes.py