Problem 93

Almost equilateral triangles

Problem 95

Almost equilateral triangles

Problem 94

It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units.
We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).
def run(limit=1e9):
    # https://en.wikipedia.org/wiki/Pell%27s_equation
    # Pells Equation and nearly equilateral triangles.pdf
    # https://www.mathblog.dk/project-euler-94-almost-equilateral-triangles/
    # https://digitalrepository.unm.edu/cgi/viewcontent.cgi?article=1010&context=math_etds
    # https://mathschallenge.net/full/almost_equilateral_triangles
    x = 2
    y = 1
    result = 0

    while 1:
        # b = a+1
        a_times_3 = 2 * x - 1
        area_times_3 = y * (x - 2)
        if a_times_3 > limit:
            break

        if a_times_3 > 0 and area_times_3 > 0 and a_times_3 % 3 == 0 and area_times_3 % 3 == 0:
            a = a_times_3 / 3
            area = area_times_3 / 3
            result += 3 * a + 1
        
        # b = a-1
        a_times_3 = 2 * x + 1
        area_times_3 = y * (x + 2)

        if a_times_3 > 0 and area_times_3 > 0 and a_times_3 % 3 == 0 and area_times_3 % 3 == 0:
            a = a_times_3 / 3
            area = area_times_3 / 3
            result += 3 * a - 1

        tmp_x = 2 * x + 3 * y
        tmp_y = 2 * y + x
        x = tmp_x
        y = tmp_y

    return result