633. Sum of Square Numbers #166
Answered
by
basharul-siddike
mah-shamim
asked this question in
Q&A
-
|
Topics: Given a non-negative integer Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Answered by
basharul-siddike
Sep 9, 2024
Replies: 1 comment 2 replies
-
|
We can utilize a two-pointer approach. Here's how we can approach the problem: Explanation:
Let's implement this solution in PHP: 633. Sum of Square Numbers <?php
/**
* @param Integer $c
* @return Boolean
*/
function judgeSquareSum($c) {
// Initialize two pointers
$a = 0;
$b = (int) sqrt($c);
// Iterate while a <= b
while ($a <= $b) {
$sumOfSquares = $a * $a + $b * $b;
if ($sumOfSquares == $c) {
return true; // Found a pair (a, b)
} elseif ($sumOfSquares < $c) {
$a++; // Increment a to increase sum
} else {
$b--; // Decrement b to decrease sum
}
}
return false; // No such pair exists
}
// Example usage:
$c1 = 5;
$c2 = 3;
echo "Result for c = $c1: " . (judgeSquareSum($c1) ? "true" : "false") . "\n"; // Output: true
echo "Result for c = $c2: " . (judgeSquareSum($c2) ? "true" : "false") . "\n"; // Output: false
?>Explanation:
Time Complexity:
Example Outputs:
This approach efficiently checks for two integers whose squares sum up to |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mah-shamim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can utilize a two-pointer approach. Here's how we can approach the problem:
Explanation:
Constraints:
c.aandbsuch thata² + b² = c.Two-pointer Approach:
ainitialized to 0, andbinitialized to the square root ofc.aandb. Ifa² + b²equalsc, returntrue.a² + b²is less thanc, incrementato increase the sum.a² + b²is greater thanc, decrementbto decrease the sum.ais less than or equal tob.false.Let's implement this solution in PHP: 633. Sum of Square Numbers
…