projecteuler.net解题记录,参考了肥猫的(第9题)

来源:互联网 发布:mac好用的相册 编辑:程序博客网 时间:2024/04/29 05:25
第9题:
Find the only Pythagorean triplet, {abc}, for which a + bc = 1000.

求出某三个数,满足a**2+b**2==c**2,且a+b+c=1000
  1. # a+b+c = 1000, 同时满足 a平方加b平方等于c平方
  2. import time
  3. start = time.time()
  4. def test():
  5.     for a in xrange(1,334):
  6.         for b in xrange(a+1,500-a/2):
  7.             if (1000-a)*(1000-b) == 500000:
  8.                 c = 1000 - a -b
  9.                 if a**2+b**2==c**2:
  10.                     print a*b*c,a,b,c
  11.                     return
  12. def test1():
  13.     for a in xrange(1,334):
  14.         if not 500000%(1000-a):
  15.             b = 1000-500000/(1000-a)
  16.             c = 1000-a-b
  17.             if a**2+b**2 == c**2:
  18.                 print a*b*c,a,b,c
  19.                 return
  20. test()
  21. print time.time()-start
  22. start = time.time()
  23. test1()
  24. print time.time()-star
其中test1花的时间微乎其微,其优化的根据是对公式进行化简:
a**2+b**2 = (1000-a-b)**2
  = 1000**2 -2000(a+b)+2ab+a**2+b**2
可得: (1000-a)(1000-b) = 500*1000
test1的时间复杂度是最小的.    
原创粉丝点击