原题地址:http://projecteuler.net/problem=9
Special Pythagorean triplet
Problem 9
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a
2 +
b
2 =
c
2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
大意是:
一个毕达哥拉斯三元组是一个包含三个自然数的集合,a<b<c,满足条件:
a2 + b2 = c2
例如:32 + 42 = 9 + 16 = 25 = 52.
已知存在并且只存在一个毕达哥拉斯三元组满足条件a + b + c = 1000。
找出该三元组中abc的乘积。
解法1:
a边从1遍历到1000,b边则从a+1遍历到1000,c当然是等于1000-a-b,而且c>b,接着判断a,b,c是否能构成一个三角形,如果能,则接着判断是否符合勾股定理
python代码如下所示:
def isTriangle(a,b,c):
if (a+b > c) and (a+c > b) and (b+c >a) :
return True
else:
return False
def isPythagorean(a,b,c):
a = a**2
b = b**2
c = c**2
if (a+b == c) or (a+c == b) or (b+c == a):
return True
else:
return False
def cal():
for i in range(1,1000):
for j in range(i+1,1000):
k = 1000-i-j
if k>j:
if isTriangle(i,j,k):
#print i,j,k
if isPythagorean(i,j,k):
return i*j*k
print cal()
注:题目的中文翻译源自http://pe.spiritzhang.com