Project Euler Problem 138

# Statement

Consider the isosceles triangle with base length, b = 16, and legs, L = 17. By using the Pythagorean theorem it can be seen that the height of the triangle, $h = \sqrt{(17^{2} - 8^{2})} = 15$, which is one less than the base length.

With b = 272 and L = 305, we get h = 273, which is one more than the base length, and this is the second smallest isosceles triangle with the property that $h = b \pm 1$.

Find L for the twelve smallest isosceles triangles for which $h = b \pm 1$ and b, L are positive integers.

# Solution

To get to the solution of this problem I started by generating Pythagorean triangles using the known formula by Euler, and started incrementing their sides until I found some of the ones with the property.

After finding those I analysed the generator numbers n and m that were used to find the the triangles, and then is when I noticed that at least the first 3 triangles which had this property
were derived starting by 2 consecutive numbers in the Fibonacci series, and more precisely the distance between each pair of the Fibonacci numbers were 3 places in the sequence, to exemplify: the first
triangle was found using (3,5) as generator, the second using (13, 21) as generators, the third using (55, 89).

I just applied that sequence to get the first twelve generator pairs and then bruteforce over the triangles generated with those pairs to find the one which has the property.

from itertools import islice

def get_triangle(m, n):
a = m * n
b = (n ** 2 - m ** 2) // 2
c = (n ** 2 + m ** 2) // 2
return (a, b, c)

def fib_generator():
i1 = 1
i2 = 1
while True:
for i in range(3):
i1, i2 = (i2, i1 + i2)
yield (i1, i2)

if __name__ == '__main__':
result = 0
for height, base, l in (get_triangle(n, m) for n, m in islice(fib_generator(), 12)):
mult = 1
while abs(((base * mult) * 2) - (height * mult)) != 1:
mult += 1
result += l * mult
print("The result is:", result)