Problem 9:Special Pythagorean triplet

原题地址: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值