2021-04-28 633. 平方数之和

633. 平方数之和

思路一:利用sqrt

为了避免溢出,需要用long。

class Solution {
    public boolean judgeSquareSum(int c) {
        // 利用sqrt
        long a = (long)Math.sqrt(c);
        for(long i=a;i>=0;i--){
            long b = (long)Math.sqrt(c-i*i);
            if((c-i*i-b*b)==0){
                return true;
            }
        }
        return false;   
    }
}

思路二:双指针

  • a = 0 , b = (long) c a=0, b=\text{(long)} \sqrt{c} a=0,b=(long)c
  • while(a<=b)
    • 如果 a 2 + b 2 = = c a^2+b^2==c a2+b2==c
      • return true;
    • 如果 a 2 + b 2 > c a^2+b^2>c a2+b2>c
      • b–;
    • 如果 a 2 + b 2 < c a^2+b^2<c a2+b2<c
      • a++;

证明:(双指针不会漏掉某种情况)
https://leetcode-cn.com/problems/sum-of-square-numbers/solution/shuang-zhi-zhen-de-ben-zhi-er-wei-ju-zhe-ebn3/

class Solution {
    public boolean judgeSquareSum(int c) {
        long a = 0, b = (long)Math.sqrt(c);
        while(a<=b){
            long tmp = a*a+b*b;
            if(c==tmp)
				return true;
            else if(c>tmp)
                a++;
            else
            	b--;
        }
        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;
            }
            System.out.print(base+"\t"+exp+"\n");
        }

      	// 例如 11 这样的用例,由于上面的 for 循环里 base * base <= c ,base == 11 的时候不会进入循环体
      	// 因此在退出循环以后需要再做一次判断
        return c % 4 != 3;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值