Problem

A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.

Given an integer n, return _the number ofsquare triples such that _1 <= a, b, c <= n.

Examples

Example 1

1
2
3
Input: n = 5
Output: 2
**Explanation** : The square triples are (3,4,5) and (4,3,5).

Example 2

1
2
3
Input: n = 10
Output: 4
**Explanation** : The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).

Constraints

  • 1 <= n <= 250

Solution

Method 1 – Brute Force Enumeration

Intuition

We want to count all ordered triples (a, b, c) such that 1 ≤ a, b, c ≤ n and a² + b² = c². Since n is small (≤ 250), we can check all possible (a, b, c) combinations.

Approach

  1. Initialize ans = 0.
  2. For each c from 1 to n:
    1. For each a from 1 to n:
      1. For each b from 1 to n:
        1. If a² + b² == c², increment ans.
  3. Return ans.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public int countTriples(int n) {
        int ans = 0;
        for (int c = 1; c <= n; c++) {
            for (int a = 1; a <= n; a++) {
                for (int b = 1; b <= n; b++) {
                    if (a * a + b * b == c * c) ans++;
                }
            }
        }
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
class Solution:
    def countTriples(self, n: int) -> int:
        ans = 0
        for c in range(1, n+1):
            for a in range(1, n+1):
                for b in range(1, n+1):
                    if a*a + b*b == c*c:
                        ans += 1
        return ans

Complexity

  • ⏰ Time complexity: O(n^3), since we check all (a, b, c) triples.
  • 🧺 Space complexity: O(1), only a counter is used.