题目

A Pythagorean triplet is a set of three natural numbers, a<b<c, for which, a2+b2=c2. For example, 32+42=9+16=25=52.

There exists exactly one Pythagorean triplet for which a+b+c=1000. Find the product abc.

解答

这道题遍历ab的各种可能组合,c1000-a-b来确定。然后a,b,c符合勾股定理,那答案就找到了。

def solution9(n):  
    x = range(1, n)  
    find = False  
  
    for a in x:  
        for b in x:  
            c = n - a - b  
            if c < 0:  
                next  
            if a**2 + b**2 == c**2:  
                res = a * b * c  
                find = True  
                break  
        if find:  
            break  
    return res

因为解这道题n=1000时,只有唯一一组数字符合,所以这里找到第一个的时候,直接return就好了。这里我没有直接return,而是跳出循环。如果函数的输入n是其它的数,而解不是唯一,那这个函数就简单改一下,就可以把各种解都拿到。