Skip to content

Instantly share code, notes, and snippets.

@iansltx
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iansltx/0b83769345042b089b2f to your computer and use it in GitHub Desktop.
Save iansltx/0b83769345042b089b2f to your computer and use it in GitHub Desktop.
Get a list of all primitive Pythagorean triples with hypotenuse <= Nmax, one per line
# pass the MB of RAM you want to use as your argument
# Nmax = 10,000 * RAM_in_MB; CPU time on an EC2 r3.8xlarge is 60s/1M Nmax
# adapted from http://stackoverflow.com/a/8263898/2476827
import sys
from numpy import mat, array
def gen_pythagorean_triples(max):
u = mat(' 1 2 2; -2 -1 -2; 2 2 3')
a = mat(' 1 2 2; 2 1 2; 2 2 3')
d = mat('-1 -2 -2; 2 1 2; 2 2 3')
m = [array([3, 4, 5])]
while m:
yield from m
g = ((i*j).getA1() for i in m for j in (u, a, d))
m = [i for i in g if i[2] <= max]
def get_nice_string(list_or_iterator):
return "\n".join(str(x) for x in list_or_iterator)
print(get_nice_string(gen_pythagorean_triples(10000 * int(sys.argv[1]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment