【題目】633. 平方數之和
給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,使得 a2 + b2 = c。
示例1:
輸入: 5
輸出: True
解釋: 1 * 1 + 2 * 2 = 5
示例2:
輸入: 3
輸出: False
【解題思路1】枚舉
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;
}
}
雙指針枚舉
class Solution {
public boolean judgeSquareSum(int c) {
if(c < 0)
return false;
int i = 0;//雙指針的左指針
int j = (int)Math.sqrt(c);//雙指針的右指針
while(i <= j){
if(i*i == c - j*j){
return true;
}else if(c - j*j < i*i){
j--;
}else{
i++;
}
}
return false;
}
}
【解題思路2】數學:費馬平方和定理(待研究)
費馬平方和定理:一個非負整數 c 能夠表示爲兩個整數的平方和,當且僅當 c 的所有形如 4k+3 的質因子的冪次均爲偶數。
對 c 進行質因數分解,再判斷形如 4k+3 的質因子的冪次是否均爲偶數
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;
}
}