Skip to content

Instantly share code, notes, and snippets.

@btilly
Created February 28, 2023 20:23
Show Gist options
  • Save btilly/86a6c99aeaba18f6a2242b740196d7fb to your computer and use it in GitHub Desktop.
Save btilly/86a6c99aeaba18f6a2242b740196d7fb to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import heapq
def gcd (m, n):
while 0 < n:
(m, n) = (n, m % n)
return m
def pythagorean_triples ():
triples = [(5, 1, 2, 1)]
while True:
(c, m, n, k) = heapq.heappop(triples)
if (1 == gcd(m, n)):
yield (k*n*n - k*m*m, 2*k*m*n, c)
heapq.heappush(triples, ((k+1)*n*n + (k+1)*m*m, m, n, k+1))
if k == 1:
if m+1 == n:
heapq.heappush(triples, ((n+1)*(n+1) + n*n, m+1, n+1, 1))
heapq.heappush(triples, ((n+2)*(n+2) + m*m, m, n+2, 1))
for t in pythagorean_triples():
if 1000 < t[2]:
break
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment