I was trying Project Euler and am stuck on this one:
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.
for i in range(1000,100,-1):
for j in range(1000,100,-1):
test = i*j
test = str(test) #turn product into string
test2 = test[2:] #take last two numbers
test2 = test2[::-1] #flip them
if test[:2] == test2: #if it's a palindrome, the first two should
print(i, "\t", j) #match the flip of last two
input("\n\nPress the ENTER key to exit.")
Nothing happens when it is run: the command line calculates, but doesn’t print anything. The program does end though.
I know the bigger numbers have more than just the first and last two numbers, but there should be few enough palindromes that I can just look through them.
Here is the next one:
Find the Pythagorean triplet whose sum is 1000.
a^2 + b^2 = c^2, a+b+c=1000
for a in range(1,32):
for b in range(1,32):
c = (a**2 + b**2)**.5
if a + b + c == 1000:
print(a,"\t",b,"\t",c)
input("\n\nPress the ENTER key to exit.")
As with the last program, there is no output… But again, it does end.
But I noticed that they both have nested for loops. Could this have something to do with it?
Both your tests are wrong. In the first example, the line
does not say what the comment says – this line strips off the first two characters from the string, leaving only the last digit. Instead of fixing this line, simply check if the whole string equals the reversed string:
In the second example, you compare approximate floating point numbers to the exact integer
1000. Since the floating-pointed numbers will have rounding errors, you don’t find an exact match. See also Floating Point Arithmetic: Issues and Limitations in the Python tutorial.You should round
cto the nearest integer, check if they really are a Pythagorean triple using pure integer arithmetic and then test if the sum is 1000.As pointed out by DSM in the comments, your loops also stop to early. the maximum sum you will find with these values is about 106.