Reputation: 135
I would like help in solving the following problem: Find the product of the triplet of a,b,c for which: a+b+c = 1000 and a^2+b^2=c^2. I have written some python code, but it doesn't output anything. Please could you tell me what is wrong with it?
for a in range(1000):
for b in range(1000-a):
c = 1000-a-b
if a**2 + b**2 == c**2:
print a*b*c
else:
break
Upvotes: 0
Views: 3102
Reputation: 5939
Your idea is correct. You have to fix your formatting and remove this break statement at the end ( this break makes you end the loop on first try. Oh and one more thing. a and b cant be 0 because it would be trivial otherwise (500**2+0**2==500**2).
def find_product(sum):
for a in range(1, sum):
for b in range(1, sum - a):
c = sum - a - b
if a**2 + b**2 == c**2:
print a*b*c
return a*b*c
else:
pass
#Keep looking! Dont end here :)
print 'No such triplet exists!'
So the result is:
>>> find_product(1000) # 200**2 + 375**2 = 425**2
31875000
Of course your code can be optimized by using some clever mathematical tricks :)
Upvotes: 1