# 633. Sum of Square Numbers

Given a non-negative integer `c`, your task is to decide whether there’re two integers `a` and `b` such that a2 + b2 = c.

Example 1:

``````Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
``````

Example 2:

``````Input: 3
Output: False
``````

``````class Solution {
public:
bool judgeSquareSum(int c) {
for (int i = sqrt(c); i >= 0; --i) {
if (i * i == c) return true;
int d = c - i * i, t = sqrt(d);
if (t * t == d) return true;
}
return false;
}
};
``````

``````class Solution {
public:
bool judgeSquareSum(int c) {
unordered_set<int> s;
for (int i = 0; i <= sqrt(c); ++i) {
s.insert(i * i);
if (s.count(c - i * i)) return true;
}
return false;
}
};
``````

``````class Solution {
public:
bool judgeSquareSum(int c) {
long a = 0, b = sqrt(c);
while (a <= b) {
if (a * a + b * b == c) return true;
else if (a * a + b * b < c) ++a;
else --b;
}
return false;
}
};
``````

``````class Solution {
public:
bool judgeSquareSum(int c) {
for (int i = 2; i * i <= c; ++i) {
if (c % i != 0) continue;
int cnt = 0;
while (c % i == 0) {
++cnt;
c /= i;
}
if (i % 4 == 3 && cnt % 2 != 0) return false;
}
return c % 4 != 3;
}
};
``````

https://leetcode.com/problems/sum-of-square-numbers/

https://leetcode.com/problems/sum-of-square-numbers/discuss/104938/simple-c-solution

https://leetcode.com/problems/sum-of-square-numbers/discuss/104930/java-two-pointers-solution

https://leetcode.com/problems/sum-of-square-numbers/discuss/104932/hashset-java-quick-solution-one-for-loop

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation