Problem 39

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p ≤ 1000, is the number of solutions maximised?

Pythagorean Theorem

a^2 + b^2 = c^2

In [1]:
import math
import time

def is_pythagorean(a, b, c):
    return (a**2 + b**2) == (c**2)

def hypotenuse(a, b):
    return math.sqrt(a**2 + b**2)

def pythagorean_combos_upto(limit):
    for a in range(1,limit+1):
        for b in range(a+1,limit+1):
            if a+b > limit:
                break
            c = math.floor(hypotenuse(a,b))
            if a+b+c <= limit and is_pythagorean(a, b, c):
                yield (a,b,c)

def get_perimeter_to_combos(limit):
    combos = {}
    for (a,b,c) in pythagorean_combos_upto(limit):
        perimeter = a + b + c
        if perimeter not in combos:
            combos[perimeter] = []
        combos[perimeter].append((a,b,c))
    return combos

In [2]:
t0 = time.time()
pc = get_perimeter_to_combos(1000)
max_k = None
for k in pc:
    if max_k is None or len(pc[k]) > len(pc[max_k]):
        max_k = k
t1 = time.time()
print('Answer:', max_k)
print('Elapsed:', t1-t0)
print('Solution Count:', len(pc[max_k]))
print('Solutions:', pc[max_k])


Answer: 840
Elapsed: 0.6716511249542236
Solution Count: 8
Solutions: [(40, 399, 401), (56, 390, 394), (105, 360, 375), (120, 350, 370), (140, 336, 364), (168, 315, 357), (210, 280, 350), (240, 252, 348)]

In [ ]: