[Project Euler]Problem 9

Problem 9:
  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.

问题9:
  寻找和为1000的毕达哥拉斯三元数(勾股数)。

思路:
  a2 + b2 = c2< a2 +2ab+ b2 =(a+b)2
  c<a+b,a+b+c=1000, 所以 a<b<c<500<a+b 。
  a<b,a+b>500,所以250<b<c<500。 

View Code
from math import ceil
def f(n):
m
=ceil(n/2)
for b in range(ceil(m/2),m):
for c in range(b+1,m):
a
=n-b-c
if a*a+b*b==c*c:
return a*b*c

优化:

  内循环中多次求平方,可以先将 1到500的平方求出来,直接查表。

View Code
from math import ceil
def f2(n):
m
=ceil(n/2)
l
=[i*i for i in range(m)]
for b in range(ceil(m/2),m):
for c in range(b+1,m):
a
=n-b-c
if l[a]+l[b]==l[c]:
return a*b*c

作者: class   发布时间: 2011-05-31