# Euler Problem 39¶

Back to overview.

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?

We are looking for right angle triangles so Pythagoras' theorem $a^2 + b^2 = c^2$ can be used. Also it must be true that $a <= b <= c$ is true for every solution. Let's start with a function that tests the given examples.

In [13]:

    def is_right_angle_triangle(a, b, c, p):
        if a + b + c != p:
            return False
        if a**2 + b**2 != c**2:
            return False
        return True

    given = [(20, 48, 52, 120), (24, 45, 51, 120), (30, 40, 50, 120)]
    for g in given:
        assert(is_right_angle_triangle(*g))
    assert(is_right_angle_triangle(29, 41, 50, 120) == False)

This seems bruteforceable. Let's try to find the solutions for p = 120.

In [16]:

    def brute_force(p):
        solutions = [(a,b, p - a - b)
            for b in range(1, p // 2 + 1)
            for a in range(1, b)
            if a*a + b*b == (p - a - b) * (p - a - b)
        ]
        return solutions

    print(brute_force(120))

    [(30, 40, 50), (24, 45, 51), (20, 48, 52)]

Looks good. Let's try for all $p <= 1000$.

In [18]:

    solutions = [(len(brute_force(p)), p) for p in range(1, 1001)]

Well, not too fast, but also not too slow. Let's get the max and we have our solution.

In [24]:

    s, p = max(solutions)
    print(p)
    assert(p == 840)

    840