题目描述
Given a integer c, your task is to decide whether there’re two integers a and b such that a^2 + b^2 = c.
样例
Given n = 5
Return true // 1 * 1 + 2 * 2 = 5
Given n = -5
Return false
代码
- 法一
import math
class Solution:
"""
@param: : the given number
@return: whether whether there're two integers
"""
def checkSumOfSquareNumbers(self, num):
# write your code here
if num < 0:
return False
for i in range(int(math.sqrt(num)), -1, -1):
if i * i == num:
return True
t = num - i * i
_t = int(math.sqrt(t))
if _t * _t == t:
return True
return False
- 法二
import math
class Solution:
"""
@param: : the given number
@return: whether whether there're two integers
"""
def checkSumOfSquareNumbers(self, num):
# write your code here
if num < 0:
return False
a = 0
b = int(math.sqrt(num))
while a <= b:
if a ^ 2 + b ^ 2 == num:
return True
elif a ^ 2 + b ^ 2 > num:
b -= 1
else:
a += 1
return False