Count Square Sum Triples

Here’s a method to count the square triples (a, b, c) such that (a^2 + b^2 = c^2) and (1 \leq a, b, c \leq n).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def countTriples(self, n: int) -> int:
        # Initialize the count of square triples
        count = 0

        # Loop through all possible values of a and b, where a and b are less than or equal to n
        for a in range(1, n + 1):
            for b in range(a, n + 1):
                # Compute the value of c based on a and b
                c = (a**2 + b**2)**0.5

                # Check if c is an integer and less than or equal to n
                if c == int(c) and c <= n:
                    # Increment the count as a valid square triple is found
                    count += 2 # Two possibilities for each (a, b, c) and (b, a, c)

        return count

In this code, we iterate over all possible combinations of (a) and (b) from 1 to (n), and for each combination, we calculate (c) using the formula (c = \sqrt{a^2 + b^2}). If (c) is an integer and less than or equal to (n), we increment the count by 2, as there are two possible arrangements of the triple: ((a, b, c)) and ((b, a, c)).