84. 给定一个正整数,判断是否存在两个整数a和吧,他们的平方数之和等于c

给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。

示例1:

输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5

示例2:

输入: 3
输出: False

暴力求解, 通过遍历组合计算是否相等,如果相等则存在,否则不存在,解答如下:

import unittest
import math

class Solution:
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        d = int(math.sqrt(c)+1)
        for i in range(d):
            for j in range(d):
                #print("i=", i, " j=", j)
                if(i*i+j*j==c):
                    return True
        return False

class TestjudgeSquareSumFunc(unittest.TestCase):
    """Test revert"""

    def test_judgeSquareSum(self):
        """Test method checkRecord()"""
        s =Solution()
        self.assertEqual(True, s.judgeSquareSum(5))
        self.assertEqual(False, s.judgeSquareSum(3))


if __name__ == '__main__':
    unittest.main()