Algorithm
Problem Name: 633. Sum of Square Numbers
Given a non-negative integer c
, decide whether there're two integers a
and b
such that a2 + b2 = c
.
Example 1:
Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3 Output: false
Constraints:
0 <= c <= 231 - 1
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
bool judgeSquareSum(int c) {
for(int a = 0, b = sqrt(c); a < = sqrt(c); a++, b = sqrt(c - a * a))
if(b * b == c - a * a) return true;
return false;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const judgeSquareSum = function(c) {
if (c < 0) return false;
const max = Math.floor(Math.sqrt(c));
for (let i = 0; i < max + 1; i++) {
if (Number.isInteger(Math.sqrt(c - i * i))) {
return true;
}
}
return false;
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def judgeSquareSum(self, c: int) -> bool:
return not all(((c - i ** 2) ** 0.5) % 1 for i in range(int(c ** 0.5) + 1))
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System;
namespace LeetCode
{
public class _0633_SumOfSquareNumbers
{
public bool JudgeSquareSum(int c)
{
int i = (int)Math.Sqrt(c);
if (i * i == c) return true;
int j = 1;
while (j < = i)
{
if (i * i + j * j == c) return true;
else if (i * i + j * j < c) j++;
else i--;
}
return false;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output