DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay