633. 平方數之和
阿新 • • 發佈:2020-11-12
給定一個非負整數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