Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hongster
Created January 4, 2016 04:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongster/636b227ac0941562c001 to your computer and use it in GitHub Desktop.
Save hongster/636b227ac0941562c001 to your computer and use it in GitHub Desktop.
Generate Primitive Pythagorean Triples using Euclid's formula.
#!/usr/bin/python
"""
Exercise in generate Primitive Pythagorean Triples using Euclid's formula.
Ref: http://bit.ly/1MOK3kY
"""
import fractions
import math
def pythagorean_triple(s, t):
"""
Returns a triple (a, b, c) based on following definition:
s > t >= 1, s and t are positive odd integers, with no common factor.
a^2 + b^2 = c^2
a = st
b = (s^2 - t^2) / 2
c = (s^2 + t^2) / 2
"""
a = s * t
b = (s**2 - t**2)>>1
c = (s**2 + t**2)>>1
return (a, b, c)
def s_t_generator(upper_bound):
"""
Generate (s,t) tuples based on the following definition:
s > t >= 1, s and t are positive odd integers, with no common factor.
`upper_bound` sets the max (inclusive) value for s.
"""
limit = upper_bound + 1
for t in xrange(1, limit - 2, 2):
for s in xrange(t + 2, limit, 2):
# Check if s & t are coprime
if fractions.gcd(s, t) != 1:
continue
yield (s, t)
def main():
for s, t in s_t_generator(9):
a, b, c = pythagorean_triple(s, t)
print "%d, %d, %d" % (a, b, c)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment