VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-given-number-is-a-perfect-square-using-binary-search/

⇱ Check if a given number is a Perfect square using Binary Search - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a given number is a Perfect square using Binary Search

Last Updated : 12 Jul, 2025

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.

Examples: 

Input: N = 4900 
Output 70 
Explanation: 
4900 is a perfect square number of 70 because 70 * 70 = 4900

Input: N = 81 
Output:
Explanation: 
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: 


Output: 
-1

 

Time Complexity: O(Logn)
Auxiliary Space: O(Logn) for recursive stack space.
 

Comment