Check given number is Perfect Square

Write a program to check given number is Perfect Square.

Example 1:

Input: num = 9
Output: Number is perfect square

Example 2:

Input: num = 8
Output: Number is not a perfect square

Approach

Java

public class PerfectSqrtNumber {

    public static void main(String[] args) {
        int x = 9;
        if (isPerfectSquare((x))
            System.out.println("Number is perfect square");
        else
            System.out.println("Number is not a perfect square");

    }

    private static boolean isPerfectSquare(int x) {
        if (x <= 1)
            return true;
        long low = 1l;
        long high = x / 2;
        long mid = 0l;
        while (low <= high) {
            mid = low + (high - low) / 2;
            if (mid * mid < x) {
                low = low + 1;
            } else if (mid * mid > x) {
                high = mid - 1;
            } else
                return true;
        }
        return false;
    }
}
//Time Complexity: O(log(n))
//Space Complexity:O(1)

C++

#include <bits/stdc++.h>
using namespace std;
//Function to check given
//number is perfect square
bool isPerfectSquare(int n)
{
    int low=1;
    int high=n;
    while(low<=high)
    {
        int mid=low+(high-low)/2;
        if(mid*mid==n)
            return true;
        else if(mid*mid>n)
           high=mid-1;
        else 
           low=mid+1;
    }
   return false;
}
int main()
{
    int n=9;
    if(isPerfectSquare(n))
       cout<<"Number is perfect square\n";
    else
       cout<<"Number is not a perfect square\n";
   return 0;
}
//Time Complexity: O(log(n))
//Space Complexity:O(1)


No comments:

Post a Comment