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");elseSystem.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;} elsereturn 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 squarebool 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;elselow=mid+1;}return false;}int main(){int n=9;if(isPerfectSquare(n))cout<<"Number is perfect square\n";elsecout<<"Number is not a perfect square\n";return 0;}//Time Complexity: O(log(n))//Space Complexity:O(1)
No comments:
Post a Comment