Check if a number is perfect square without finding square root - GeeksforGeeks

09 Apr, 2021
Check whether a number is a perfect square or not without finding its square root. 
Examples: 
Input : n = 36 Output : Yes
Input : n = 12 Output : No 
We have discussed a method to check if a number is perfect square.
Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) then check if squaring it makes n. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number is perfect// square without finding square root#include <bits/stdc++.h>using namespace std; bool isPerfectSquare(int n){    for (int i = 1; i * i <= n; i++) {         // If (i * i = n)        if ((n % i == 0) && (n / i == i)) {            return true;        }    }    return false;} // Driver codeint main(){    long long int n = 36;    if (isPerfectSquare(n))        cout << "Yes";    else        cout << "No";     return 0;}
// Java program to check if a number is perfect// square without finding the square rootpublic class GfG {     static boolean isPerfectSquare(int n)    {        for (int i = 1; i * i <= n; i++) {             // If (i * i = n)            if ((n % i == 0) && (n / i == i)) {                return true;            }        }        return false;    }     public static void main(String[] args)    {         int n = 36;         if (isPerfectSquare(n))            System.out.println("Yes");        else            System.out.println("No");    }} // This code is contributed by Rituraj Jain
# Python3 program to check if a number is# perfect square without finding square root # from math import sqrt function  def isPerfectSquare(n) :     i = 1    while(i * i<= n):                 # If (i * i = n)        if ((n % i == 0) and (n / i == i)):            return True                     i = i + 1    return False # Driver codeif __name__ == "__main__" :     n = 36    if (isPerfectSquare(n)):        print("Yes, it is a perfect square.")    else :        print("No, it is not a perfect square.")     # This code is contributed by Ryuga
// C# program to check if a number is perfect// square without finding the square rootusing System; public class GfG {     static bool isPerfectSquare(int n)    {        for (int i = 1; i * i <= n; i++) {             // If (i * i = n)            if ((n % i == 0) && (n / i == i)) {                return true;            }        }        return false;    }     public static void Main()    {         int n = 36;         if (isPerfectSquare(n))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }}/*This code is contributed by Rajput-Ji*/
<?php// PHP program to check if a number is perfect// square without finding square root function isPerfectSquare($n){    for ($i = 1; $i * $i <= $n; $i++) {         // If (i * i = n)        if (($n % $i == 0) && ($n / $i == $i)) {            return true;        }    }    return false;}     // Driver code$n = 36;if (isPerfectSquare($n))    echo "Yes";    else    echo "No"; // This code is contributed// by Akanksha Rai
<script>// JavaScript program to check if a number is perfect// square without finding square root function isPerfectSquare(n){    for (let i = 1; i * i <= n; i++) {         // If (i * i = n)        if ((n % i == 0) && (Math.floor(n / i) == i)) {            return true;        }    }    return false;} // Driver code     let n = 36;    if (isPerfectSquare(n))        document.write("Yes");    else        document.write("No");    // This code is contributed by Surbhi Tyagi.</script>
Output: 
Yes
Time Complexity : O(sqrt(N))
Method 2:The idea is to use binary search to find a number in range 1 to n whose square is equal to n, such that at each iteration the problem statement reduces to half [1 to n/2-1 OR n/2 to n].
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Program to find if x is a// perfect square.bool isPerfectSquare(int x){     long long left = 1, right = x;       while (left <= right)    {        long long mid = (left + right) / 2;                // Check if mid is perfect square        if (mid * mid == x)        {            return true;        }                 // Mid is small -> go right to increase mid        if (mid * mid < x)        {            left = mid + 1;        }               // Mid is large -> to left to decrease mid        else        {            right = mid - 1;        }    }    return false;} // Driver Codeint main(){    int x = 2500;       // Function Call    if (isPerfectSquare(x))        cout << "Yes";    else        cout << "No";    return 0;}
// Java program for above approachclass GFG{         // Program to find if x is a    // perfect square.    static boolean isPerfectSquare(int num)    {        long left = 1, right = num;                 while (left <= right)        {            long mid = (left + right) / 2;                       // Check if mid is perfect square            if (mid * mid == num)            {                return true;            }                        // Mid is small -> go right to increase mid            if (mid * mid < num)            {                left = mid + 1;            }                       // Mid is large -> to left to decrease mid            else            {                right = mid - 1;            }        }        return false;    }         // Driver code    public static void main(String[] args)    {        int x = 2500;                 // Function Call        if (isPerfectSquare(x))            System.out.print("Yes");        else            System.out.print("No");    }}
# Python program for above approach # Program to find if x is a# perfect square.def isPerfectSquare(x):         left = 1    right = x         while (left <= right):               mid = (left + right) >> 1                 # Check if mid is perfect square        if ((mid * mid) == x):            return True                 # Mid is small -> go right to increase mid        if (mid * mid < x):            left = mid + 1                   # Mid is large -> to left to decrease mid        else:            right = mid - 1    return False # Driver codeif __name__ == "__main__":     x = 2500     # Function Call  if (isPerfectSquare(x)):      print("Yes")  else:      print("No")
// C# program for above approachusing System;class GFG{     // Program to find if x is a// perfect square.static bool isPerfectSquare(int x){  long left = 1, right = x;   while (left <= right)  {    long mid = (left + right) / 2;     // Check if mid is perfect    // square    if (mid * mid == x)    {      return true;    }     // Mid is small -> go right to    // increase mid    if (mid * mid < x)    {      left = mid + 1;    }     // Mid is large -> to left    // to decrease mid    else    {      right = mid - 1;    }  }  return false;}      // Driver codepublic static void Main(string[] args){  int x = 2500;   // Function Call  if (isPerfectSquare(x))    Console.Write("Yes");  else    Console.Write("No");}} // This code is contributed by Rutvik_56
<script> // Javascript program for above approach // Program to find if x is a// perfect square.function isPerfectSquare(x){     let left = 1, right = x;       while (left <= right)    {        let mid = parseInt((left + right) / 2);                // Check if mid is perfect square        if (mid * mid == x)        {            return true;        }                 // Mid is small -> go right to increase mid        if (mid * mid < x)        {            left = mid + 1;        }               // Mid is large -> to left to decrease mid        else        {            right = mid - 1;        }    }    return false;} // Driver Codelet x = 2500; // Function Callif (isPerfectSquare(x))    document.write("Yes");else    document.write("Yes");     // This code is contributed by rishavmahato348 </script>
Output: 
Yes
Time Complexity : O(log(N))Space Complexity: O(1)
mukul166
ankthon
Akanksha_Rai
rituraj_jain
Rajput-Ji
dkp1903
rubansal
gp6
oreo
rutvik_56
ghantsriharsha
surbhityagi15
rishavmahato348
maths-perfect-square
Technical Scripter 2018
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers