【题目】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;
}
}