Check if a given number N is a perfect square or not. If yes then return the number of which it is a perfect square, Else print -1.
Input: N = 4900
4900 is a perfect square number of 70 because 70 * 70 = 4900
Input: N = 81
81 is a perfect square number of 9 because 9 * 9 = 81
Approach: To solve the problem mentioned above we will use the Binary Search Algorithm.
- Find the mid element from the start and last value and compare the value of the square of mid(mid*mid) with N.
- If it is equal then return the mid otherwise check if the square(mid*mid) is greater than N then recursive call with the same start value but changed last to mid-1 value and if the square(mid*mid) is less than the N then recursive call with the same last value but changed start value.
- If the N is not a square root then return -1.
Below is the implementation of above approach:
Time Complexity: O(Logn)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if a number is a perfect square having all its digits as a perfect square
- Find smallest perfect square number A such that N + A is also a perfect square number
- Check if a number is perfect square without finding square root
- Smallest N digit number whose sum of square of digits is a Perfect Square
- Count numbers upto N which are both perfect square and perfect cube
- Find square root of number upto given precision using binary search
- Check if given number is perfect square
- Check perfect square using addition/subtraction
- Meta Binary Search | One-Sided Binary Search
- Check if the sum of a subarray within a given range is a perfect square or not
- Check whether the number can be made perfect square after adding 1
- Check whether the number can be made perfect square after adding K
- Find the Next perfect square greater than a given number
- Largest factor of a given number which is a perfect square
- Probability of getting a perfect square when a random number is chosen in a given range
- Find minimum number to be divided to make a number a perfect square
- Number of times the largest perfect square number can be subtracted from N
- Previous perfect square and cube number smaller than number N
- Kth Smallest element in a Perfect Binary Search Tree
- Check if product of array containing prime numbers is a perfect square
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.