平方数之和(双指针 | 数学)
给定一个非负整数
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;
}
}
该博客探讨如何判断非负整数c是否能表示为两个整数a和b的平方和。文章介绍了两种方法:一是利用sqrt函数结合双指针策略,初始化a=0,b=sqrt(c),通过调整a和b来寻找解;二是介绍了费马平方和定理,指出c的特定质因子幂次必须为偶数时,c才可表示为平方和。
&spm=1001.2101.3001.5002&articleId=116240794&d=1&t=3&u=0160575aa94e457f8572bac7f2c95f17)
1394

被折叠的 条评论
为什么被折叠?



