Problem 90

Right triangles with integer coordinates

Problem 92

Right triangles with integer coordinates

Problem 91

The points P (x1, y1) and Q (x2, y2) are plotted at integer co-ordinates and are joined to the origin, O(0,0), to form ΔOPQ.

There are exactly fourteen triangles containing a right angle that can be formed when each co-ordinate lies between 0 and 2 inclusive; that is,
0 ≤ x1, y1, x2, y2 ≤ 2.

Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed?
from math import floor
from tools import gcd


def num_triangles(limit, x, y):
    tmp = gcd(x, y)
    return min(floor((limit - x)/(y // tmp)), floor(y / (x // tmp))) + \
        min(floor((limit - y)/(x // tmp)), floor(x / (y // tmp)))


def run(limit=50):
    count = 0
    # all triangles with right-a at the origin
    count += limit**2
    # all triangles with right-a on x=0 or y=0
    count += 2 * limit**2

    for y in range(1, limit + 1):
        for x in range(y, limit + 1):
            nt = num_triangles(limit, x, y)
            if x == y:
                count += nt
            else:
                count += 2 * nt

    return count


def run_slow_slope_testing(limit=51):
    # Brute force with slope testing.
    m = limit**2

    total = 0
    for k in range(1, m - 1):
        for j in range(k + 1, m):
            x1 = k % limit
            y1 = k / limit
            x2 = j % limit
            y2 = j / limit
            if (y2 * y1 == -x1 * x2) or (y2 * (y2 - y1) == -x2 * (x2 - x1)) or -y1 * (y2 - y1) == x1 * (x2 - x1):
                total += 1

    return total