Last active
December 17, 2016 10:38
-
-
Save goulu/21c67590c5fa96d1c7b95e3c425c90f1 to your computer and use it in GitHub Desktop.
An inefficient way to generate Pythagorean triples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools, math | |
def triples(): | |
""" generates Pythagorean triples sorted by z,y,x with x<y<z | |
""" | |
for z in itertools.count(5): | |
for y in range(z-1,3,-1): | |
x=math.sqrt(z*z-y*y) | |
if x<y and abs(x-round(x))<1e-12: | |
yield (int(x),y,z) | |
#Euler Problem 9 | |
for (a,b,c) in triples(): | |
if a+b+c==1000: | |
print(a,b,c,a*b*c) | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
just to illustrate a much better method http://stackoverflow.com/questions/575117/generating-unique-ordered-pythagorean-triplets/41146390#41146390 in my blog article