import time def pythagorean_triple(s): """ Yield all Pythagorean triples that sum to positive integer s https://e...content-available-to-author-only...a.org/wiki/Pythagorean_triple says that all triples can be generated by a=k*(m*m-n*n) b=k*2*m*n c=k*(m*m+n*n) so from a+b+c=s follows k*2* m*(m+n)=s """ if s % 2: return # No triples sum to an odd number factors=[] for d in range(1,int(s**.5)+1): if s%d==0: factors.append(d) if s>d*d: factors.append(s//d) factors.sort() for k in factors: q=s//k # = 2* m*(m+n) if q%2==0: p=q/2 # = m*(m+n) for m in factors: # m is a factor of p and so a factor of s if p%m==0: n=p//m-m if 0<n and n<m: a=k*(m*m-n*n) b=k*2*m*n c=k*(m*m+n*n) yield(a,b,c) def test(s): start = time.time() print [[a , b , c] for a, b, c in pythagorean_triple(s)] print 'Time taken', time.time() - start test(1000) test(1356780) test(7064950394940)
Standard input is empty
[[375, 200, 425], [375, 200, 425]] Time taken 0.000114917755127 [[542712, 226130, 587938], [226130, 542712, 587938], [339195, 452260, 565325]] Time taken 0.000249862670898 [[2825980157976L, 1177491732490L, 3061478504474L], [1177491732490L, 2825980157976L, 3061478504474L], [1766237598735L, 2354983464980L, 2943729331225L]] Time taken 1.31435990334