Sum of Square number

'''
class Solution {
public:
bool isperfectsquare(int n){
int root = sqrt(n);
if(root*root==n) return true;
else return false;
}

bool judgeSquareSum(int c) {
    int x = 0;
    int y= c;
    while(x<=y){
        if(isperfectsquare(x) && isperfectsquare(y))
          return true;
        else if(!isperfectsquare(y)){
            y = (int)sqrt(y)*(int)sqrt(y);
            x = c-y;
        } 
        else{
            x = ((int)sqrt(x) + 1)*((int)sqrt(x) + 1);
            y = c-x;
        }
    }
    return false;
}

};
// yeh bhi ek process hai optimal
class Solution {
public:
bool judgeSquareSum(int c) {
long long x = 0; // Start x at 0
long long y = sqrt(c); // Start y at the square root of c

    while (x <= y) {
        long long sum = x * x + y * y;  // Compute sum of squares
        
        if (sum == c) {
            return true;                // Found a pair where x² + y² = c
        } else if (sum < c) {
            x++;                        // Increase x to increase the sum
        } else {
            y--;                        // Decrease y to decrease the sum
        }
    }
    
    return false;                       // No valid pair found
}

};
'''

Comments (0)