Sum of Square Numbers

medium math two pointers binary search

Problem

Given a non-negative integer c, return true if and only if there exist non-negative integers a, b such that a² + b² = c.

Inputc = 5
Outputtrue
1² + 2² = 5.

def judge_square_sum(c):
    lo, hi = 0, int(c ** 0.5)
    while lo <= hi:
        s = lo * lo + hi * hi
        if s == c:
            return True
        elif s < c:
            lo += 1
        else:
            hi -= 1
    return False
function judgeSquareSum(c) {
  let lo = 0, hi = Math.floor(Math.sqrt(c));
  while (lo <= hi) {
    const s = lo * lo + hi * hi;
    if (s === c) return true;
    else if (s < c) lo++;
    else hi--;
  }
  return false;
}
class Solution {
    public boolean judgeSquareSum(int c) {
        long lo = 0, hi = (long) Math.sqrt(c);
        while (lo <= hi) {
            long s = lo * lo + hi * hi;
            if (s == c) return true;
            else if (s < c) lo++;
            else hi--;
        }
        return false;
    }
}
bool judgeSquareSum(int c) {
    long lo = 0, hi = (long) sqrt((double) c);
    while (lo <= hi) {
        long s = lo * lo + hi * hi;
        if (s == c) return true;
        else if (s < c) lo++;
        else hi--;
    }
    return false;
}
Time: O(√c) Space: O(1)