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
这道题要注意两个测试用例:
2 , return true 。
2147482647,return false。
public boolean judgeSquareSum(int c) {
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i <= Math.sqrt(c); i++) {
set.add(i * i);
if (set.contains(c - i * i)) {
return true;
}
}
return false;
}
有大神用了类似于二分查找的思想。
public class Solution {
public boolean judgeSquareSum(int c) {
if (c < 0) {
return false;
}
int left = 0, right = (int)Math.sqrt(c);
while (left <= right) {
int cur = left * left + right * right;
if (cur < c) {
left++;
} else if (cur > c) {
right--;
} else {
return true;
}
}
return false;
}
}
Approach #3 Using sqrt function [Accepted]
Algorithm
Check if √c−a2 turns out to be an integer.
Java
public class Solution { public boolean judgeSquareSum(int c) { for (long a = 0; a * a <= c; a++) { double b = Math.sqrt(c - a * a); if (b == (int) b) return true; } return false; } }
Complexity Analysis
-
Time complexity : O(√clog(c)). We iterate over √c values for choosing a. For every a chosen, finding square root of c−a2 takes O(log(c)) time in the worst case.
-
Space complexity : O(1). Constant extra space is used.
Approach #4 Using Binary Search [Accepted]
Algorithm
Another method to check if c−a2 is a perfect square, is by making use of Binary Search.
Java
public class Solution { public boolean judgeSquareSum(int c) { for (long a = 0; a * a <= c; a++) { int b = c - (int)(a * a); if (binary_search(0, b, b)) return true; } return false; } public boolean binary_search(long s, long e, int n) { if (s > e) return false; long mid = s + (e - s) / 2; if (mid * mid == n) return true; if (mid * mid > n) return binary_search(s, mid - 1, n); return binary_search(mid + 1, e, n); } }
Complexity Analysis
-
Time complexity : O(√clog(c)). Binary search taking O(log(c)) in the worst case is done for √c values of a.
-
Space complexity : O(log(c)). Binary Search will take O(log(c)) space.
Approach #5 Fermat Theorem [Accepted]:
Algorithm
这个方法基于费马的平方和定理:
任何正整数 n 是两个平方数之和的充分必要条件是: n 的任意满足 (4k+3) 的素数因子都满足出现了偶数次。
Interested reader can refer to this documentation.
Java
public class Solution { public boolean judgeSquareSum(int c) { for (int i = 2; i * i <= c; i++) { int count = 0; if (c % i == 0) { while (c % i == 0) { count++; c /= i; } if (i % 4 == 3 && count % 2 != 0) return false; } } return c % 4 != 3; } }
Complexity Analysis
-
Time complexity : O(√clog(c)). We find the factors of c and their count using repeated division. We check for the factors in the range [0,√c]. The maximum number of times a factor can occur(repeated division can be done) is log(n)(considering 2 as the only factor, c=2x. Thus, x=log(c)).
-
Space complexity : O(1). Constant space is used.