Sum of Square Numbers - Problem
You're given a non-negative integer c, and your task is to determine whether there exist two integers a and b such that a² + b² = c.
In other words, you need to find if the given number c can be expressed as the sum of two perfect squares.
Note: The integers a and b can be zero, negative, or positive, but since we're dealing with squares, we only need to consider non-negative values (as (-x)² = x²).
Examples:
c = 5→true(because 1² + 2² = 1 + 4 = 5)c = 3→false(no two squares sum to 3)c = 0→true(because 0² + 0² = 0)
Input & Output
example_1.py — Basic positive case
$
Input:
c = 5
›
Output:
true
💡 Note:
5 can be expressed as 1² + 2² = 1 + 4 = 5, so the answer is true.
example_2.py — No solution case
$
Input:
c = 3
›
Output:
false
💡 Note:
There are no two integers a and b such that a² + b² = 3. We can verify: 0²+0²=0, 0²+1²=1, 1²+1²=2, 0²+2²=4. None equal 3.
example_3.py — Edge case with zero
$
Input:
c = 0
›
Output:
true
💡 Note:
0 can be expressed as 0² + 0² = 0 + 0 = 0, so the answer is true.
Constraints
- 0 ≤ c ≤ 231 - 1
- Both a and b can be zero, positive, or negative
- Since we're dealing with squares, we only need to consider non-negative values
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Place left pointer at 0, right pointer at √c
2
Calculate
Compute left² + right² and compare with target c
3
Adjust
Move left forward if sum too small, move right backward if sum too large
4
Converge
Continue until found or pointers meet
Key Takeaway
🎯 Key Insight: The two pointers approach works because as we increase 'a', the sum increases, and as we increase 'b', the sum also increases. This monotonic property allows us to eliminate impossible combinations efficiently.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code