Count Square Sum Triples - Problem

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

Given an integer n, return the number of square triples such that 1 ≤ a, b, c ≤ n.

For example, if n = 5, the square triples are (3,4,5) and (4,3,5), so the answer is 2.

Input & Output

Example 1 — Basic Case
$ Input: n = 5
Output: 2
💡 Note: The square triples are (3,4,5) and (4,3,5). Both satisfy 3² + 4² = 9 + 16 = 25 = 5² and all values are ≤ 5.
Example 2 — Small Range
$ Input: n = 3
Output: 0
💡 Note: No valid square triples exist with all values ≤ 3. The smallest Pythagorean triple is (3,4,5) but 4 and 5 exceed the limit.
Example 3 — Larger Range
$ Input: n = 10
Output: 4
💡 Note: Valid triples: (3,4,5), (4,3,5), (6,8,10), (8,6,10). Each satisfies the Pythagorean theorem with all values ≤ 10.

Constraints

  • 1 ≤ n ≤ 250

Visualization

Tap to expand
Count Square Sum Triples INPUT n = 5 Valid range: 1 to 5 1 2 3 4 5 Find triples where: a² + b² = c² a b c ALGORITHM STEPS 1 Loop a: 1 to n for a = 1, 2, 3, 4, 5 2 Loop b: a to n for b = a to 5 3 Calculate c c = sqrt(a² + b²) 4 Check conditions c is integer and c <= n Checking pairs: a=3, b=4: sqrt(9+16)=5 OK a=4, b=3: sqrt(16+9)=5 OK a=1, b=2: sqrt(1+4)=2.2 X a=2, b=3: sqrt(4+9)=3.6 X a=3, b=5: sqrt(9+25)=5.8 X FINAL RESULT Output 2 Found Triples: Triple 1: (3, 4, 5) 3² + 4² = 9 + 16 = 25 = 5² Triple 2: (4, 3, 5) 4² + 3² = 16 + 9 = 25 = 5² 2 Valid Triples within range 1-5 Key Insight: Two Loop with Square Root: For each pair (a, b), compute c = sqrt(a² + b²). If c is a perfect integer and c <= n, we found a valid triple. This O(n²) approach avoids checking all possible c values. TutorialsPoint - Count Square Sum Triples | Two Loop with Square Root Approach
Asked in
Google 25 Microsoft 20 Apple 15
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen