Count Square Sum Triples
EasyUpdated: Aug 2, 2025
Practice on:
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
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2
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
- Initialize ans = 0.
- For each c from 1 to n:
- For each a from 1 to n:
- For each b from 1 to n:
- If a² + b² == c², increment ans.
- For each b from 1 to n:
- For each a from 1 to n:
- Return ans.
Code
Java
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;
}
}
Python
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.