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
方法1: hash
易错点:
直接i* i会溢出,能变小就不要变大。ceil也会溢出。
Complexity
Time complexity: O©
Space complexity: O(sqrt©)
class Solution {
public:
bool judgeSquareSum(int c) {
unordered_set<int> hash;
for (int i = 0; i <= floor(sqrt(c)); i++) {
hash.insert(i * i);
if (hash.find(c - i * i) != hash.end()) return true;
}
return false;
}
};
方法2: binary search
思路:
方法3: Fermat’s Theorem on sum of two squares
思路:
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;
}
};