给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = 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
解法:
class Solution:
def judgeSquareSum(self, c: int) -> bool:
if c <= 2:
return True
while c % 2 == 0:
c = c // 2
p = 3
while p * p <= c:
index = 0
while c % p == 0:
index += 1
c = c // p
if (p % 4 == 3) and (index % 2 == 1):
return False
p += 2
return c % 4 == 1