平方数之和(双指针 | 数学)
给定一个非负整数
c
,你要判断是否存在两个整数a
和b
,使得a² + b² = c
。
使用 sqrt函数
class Solution {
public boolean judgeSquareSum(int c) {
for (long a = 0; a * a <= c; a++) {//如果不用long a*a会溢出
double b = Math.sqrt(c - a * a);
if (b == (int) b) {//利用精度 判断是否能够开平方
return true;
}
}
return false;
}
}
双指针解法
假设 a ≤ b,初始化 a=0,b=sqrt( c ),进行如下操作:
- 如果 a² + b² = c ,我们找到了题目要求的一个解,返回 true;
- 如果 a² + b² < c,此时需要将 a 的值加 1,继续查找;
- 如果 a² + b² >c, 此时需要将 b 的值减 1 , 继续查找。
class Solution {
public boolean judgeSquareSum(int c) {
long left = 0;
long right = (long) Math.sqrt(c);
while (left <= right) {
long sum = left * left + right * right;
if (sum == c) {
return true;
} else if (sum > c) {
right--;
} else {
left++;
}
}
return false;
}
}
费马平方和定理
一个非负整数 c 如果能够表示为两个整数的平方和,当且仅当 c 的所有形如 4k + 3 的质因子的幂均为偶数。
class Solution {
public boolean judgeSquareSum(int c) {
for (int base = 2; base * base <= c; base++) {
// 如果不是因子,枚举下一个
if (c % base != 0) {
continue;
}
// 计算 base 的幂
int exp = 0;
while (c % base == 0) {
c /= base;
exp++;
}
// 根据 Sum of two squares theorem 验证
if (base % 4 == 3 && exp % 2 != 0) {
return false;
}
}
// 例如 11 这样的用例,由于上面的 for 循环里 base * base <= c ,base == 11 的时候不会进入循环体
// 因此在退出循环以后需要再做一次判断
return c % 4 != 3;
}
}