Integer Right Triangles¶

If a right triangle has integer side lengths, the side lengths are a Pythagorean triple. In problem 9, we wrote a generator for primitive Pythagorean triples based off of Euclid's formula. We can modify that generator to cut off after the triplets have passed a maximum perimeter. Note that a triangle with side lengths generated by Euclid's formula will have perimeter $2m^2 + 2mn$.

In [1]:
from itertools import count

def primitive_pythagorean_triplets(max_perim):
    for m in count(2):
        if 2*m^2 + 2*m > max_perim:
            break

        for n in range(1, m):
            if not ((m % 2) != (n % 2)) or gcd(m, n) != 1:
                continue
            
            a = m^2 - n^2
            b = 2*m*n
            c = m^2 + n^2
            
            if a + b + c > max_perim:
                break
            
            yield (a, b, c)

Now we can just iterate through our new generator and group each triangle by their perimeters. We also multiply to consider non-primitive triplets.

In [2]:
max_perim = 1000
perimeters = dict()
for (a, b, c) in primitive_pythagorean_triplets(max_perim):
    for k in count(1):
        perimeter = k * (a + b + c)
        if perimeter > max_perim:
            break
        
        if perimeter not in perimeters:
            perimeters[perimeter] = set()
        perimeters[perimeter].add((k*a, k*b, k*c))

Our answer is whichever perimeter has the highest total.

In [3]:
p = max(perimeters, key=lambda x: len(perimeters[x]))
p
Out[3]:
840

There are eight right triangles with this perimeter.

In [4]:
perimeters[p]
Out[4]:
{(105, 360, 375),
 (140, 336, 364),
 (210, 280, 350),
 (252, 240, 348),
 (315, 168, 357),
 (350, 120, 370),
 (390, 56, 394),
 (399, 40, 401)}

Related sequences¶

  • Number of integer right triangles with perimeter $n$: A024155

Copyright (C) 2025 filifa¶

This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license and the BSD Zero Clause license.