题目来源:LeetCode_633
今天这题很快就写出来了,因为今天在进入LeetCode时候不知道哪里瞟到了一眼双指针,看完题目以后就直接用双指针的想法,很快就做出来了。
左指针从0开始,右指针从Math.Sqrt©开始(注意要强制转换成int型)
对左指针和右指针的平方和与c进行比较,如果小于就令左指针+1,如果大于就令右指针-1,循环得到结果。
public boolean judgeSquareSum(int c) {
int right =(int) Math.sqrt(c);
int left = 0;
while(left<=right ){
if((right*right + left * left)==c) return true;
else if((right*right + left * left)>c){
right --;
}else{
left ++;
}
}
return false;
}
看了一下答案,还有枚举的方法:
初始化a=0,a不断+1,看对应的b是否存在。
class Solution {
public boolean judgeSquareSum(int c) {
int max = (int)Math.sqrt(c);
for (int a = 0; a <= max; a++) {
int b = (int)Math.sqrt(c - a * a);
if (a * a + b * b == c) return true;
}
return false;
}
}
最后还有费马平方和的方法,数学证明
当且仅当一个自然数的质因数分解中,满足 4k+3 形式的质数次方数均为偶数时,该自然数才能被表示为两个平方数之和。
因此我们对 c 进行质因数分解,再判断满足 4k+3 形式的质因子的次方数是否均为偶数即可。
public boolean judgeSquareSum(int c) {
for (int i = 2, cnt = 0; i * i <= c; i++, cnt = 0) {
while (c % i == 0 && ++cnt > 0) c /= i;
if (i % 4 == 3 && cnt % 2 != 0) return false;
}
return c % 4 != 3;
}