import time def find_pythagorean(s): """ Yield all Pythagorean triples that sum to positive integer s this function is from http://c...content-available-to-author-only...e.com/questions/60652/project-euler-9-pythagorean-triplets/60671#comment-110333 """ count=0 if s % 2: return # No triples sum to an odd number hs2 = s * s / 2 for a in xrange(1, int(s * (1 - .5**.5)) + 1): if (hs2 - s * a) % (s - a) == 0: b = (hs2 - s * a) / (s - a) c=s-a-b if a+b+c>37: count=1 else: count=0 return(count) 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 """ count=0 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) if a+b+c>37: count=1 else: count=0 return(count) def test(s,ntimes): cnt=0 start = time.time() for i in range(ntimes): cnt=find_pythagorean(s) diff_time1=time.time() - start start = time.time() for i in range(ntimes): cnt=pythagorean_triple(s) diff_time2=time.time() - start print((s, diff_time1, diff_time2, diff_time1/diff_time2, ntimes)) if cnt==1234567: print(cnt) print(("a+b+c", "sec(simple alg)", "sec(euler alg)", "simple/euler", "executions")) test(770,1000) test(1000,1000) test(1006,1000) test(10010,1000) test(10000,1000) test(10006,1000) test(102102,10) test(100000,10) test(100042,10) test(1000000,1) test(1000018,1)
Standard input is empty
('a+b+c', 'sec(simple alg)', 'sec(euler alg)', 'simple/euler', 'executions') (770, 0.04948687553405762, 0.03587198257446289, 1.3795411344029562, 1000) (1000, 0.06376004219055176, 0.049881935119628906, 1.278219099512475, 1000) (1006, 0.0630950927734375, 0.009338855743408203, 6.756190962471279, 1000) (10010, 0.6293511390686035, 0.10950207710266113, 5.747389964836648, 1000) (10000, 0.6231749057769775, 0.11575698852539062, 5.3834754490031305, 1000) (10006, 0.62192702293396, 0.01711297035217285, 36.34243559914736, 1000) (102102, 0.20213890075683594, 0.0037381649017333984, 54.07436698769054, 10) (100000, 0.20229697227478027, 0.0025560855865478516, 79.14327021733047, 10) (100042, 0.20339393615722656, 0.00048613548278808594, 418.38940657184895, 10) (1000000, 0.22823405265808105, 0.0005497932434082031, 415.1270598438855, 1) (1000018, 0.22992205619812012, 0.00013709068298339844, 1677.1530434782608, 1)