给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
示例 1:
输入:c = 5
输出:true
解释:1 * 1 + 2 * 2 = 5
示例 2:
输入:c = 3
输出:false
示例 3:
输入:c = 4
输出:true
示例 4:
输入:c = 2
输出:true
示例 5:
输入:c = 1
输出:true
提示:
0 <= c <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-square-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力
class Solution: def judgeSquareSum(self, c: int) -> bool: for a in range(9999): b=c-a**2 if b<0: return False root = math.sqrt(b) if int(root + 0.5) ** 2 == b: return True return False
数学
class Solution: def judgeSquareSum(self, c: int) -> bool: i = 2 while i * i <= c: if c % i == 0: cnt = 0 while c % i == 0: c //= i cnt += 1 if i % 4 == 3 and cnt % 2 != 0: return False i += 1 return c % 4 != 3