Skip to content

Instantly share code, notes, and snippets.

@mertcanekiz
Created January 15, 2018 02:06
Show Gist options
  • Save mertcanekiz/2dce4566904eb4e8725d1803645be88d to your computer and use it in GitHub Desktop.
Save mertcanekiz/2dce4566904eb4e8725d1803645be88d to your computer and use it in GitHub Desktop.
Python code for generating Pythagorean triples with given perimeter
def gen_pythagorean_triple(p, primitive=True):
mlimit = int((p/2)**0.5)+1
for m in range(2, mlimit):
if (p//2) % m == 0:
if m % 2 == 0:
k = m + 1
else:
k = m + 2
while k < 2*m and k <= p // (2*m):
if p // (2*m) % k == 0 and gcd(k, m) == 1:
d = 1 if primitive else p // 2 // (k*m)
n = k - m
a = d*(m*m - n*n)
b = 2*d*m*n
c = d*(m*m + n*n)
if a+b+c == p: yield a, b, c
k += 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment