[go: up one dir, main page]

DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Sum of Square Numbers

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

Example 1:

Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: c = 3
Output: false

Constraints:

  • 0 <= c <= 231 - 1

SOLUTION:

import math

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        beg = 0
        end = num
        while beg <= end:
            mid = (beg + end) // 2
            if mid * mid == num:
                return True
            elif beg == end:
                break
            elif mid * mid > num:
                end = mid
            else:
                beg = mid + 1
        return False

    def judgeSquareSum(self, c: int) -> bool:
        k = 1 + int(math.sqrt(c))
        for i in range(0, k):
            if self.isPerfectSquare(c - i * i):
                return True
        return False
Enter fullscreen mode Exit fullscreen mode

Top comments (0)