動機

就開根號

Problem

Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

 

Example 1:

Input: c = 5Output: trueExplanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: c = 3Output: false

Example 3:

Input: c = 4Output: true

Example 4:

Input: c = 2Output: true

Example 5:

Input: c = 1Output: true

 

Constraints:

  • 0 <= c <= 231 - 1

Sol

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        n = math.ceil(math.sqrt(c))
        tbl = set()
        [tbl.add(x**2) for x in range(0,n+1)]
        return any((c-n in tbl) for n in tbl)