The Wayback Machine - https://web.archive.org/web/20240909212428/https://www.geeksforgeeks.org/check-if-a-number-is-perfect-square-without-finding-square-root/
Open In App

Check if a number is perfect square without finding square root

Last Updated : 27 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
51.29%
12.2K

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 

Recommended Practice

Method 1:
The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. 

Below is the implementation:

C++




// 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 code
int main()
{
    long long int n = 36;
    if (n == 0 || isPerfectSquare(n))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java




// Java program to check if a number is perfect
// square without finding the square root
public 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 (n == 0 || isPerfectSquare(n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Rituraj Jain


Python3




# 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 code
if __name__ == "__main__" :
 
    n = 36
    if (isPerfectSquare(n)):
        print("Yes, it is a perfect square.")
    elif n == 0:
        print("Yes, it is a perfect square.")
    else :
        print("No, it is not a perfect square.")
 
    # This code is contributed by Ryuga


C#




// C# program to check if a number is perfect
// square without finding the square root
using 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 (n == 0 || isPerfectSquare(n))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
/*This code is contributed by Rajput-Ji*/


PHP




<?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 ($n == 0 || isPerfectSquare($n))
    echo "Yes";    
else
    echo "No";
 
// This code is contributed
// by Akanksha Rai


Javascript




<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 (n == 0 || isPerfectSquare(n))
        document.write("Yes");
    else
        document.write("No");
 
 
 
 
// This code is contributed by Surbhi Tyagi.
</script>


Output

Yes

Time Complexity : O(sqrt(N))
Auxiliary Space: O(1)

Method 2:
The idea is to use binary search to find a number in the 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].

Below is the implementation:

C++




// 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 Code
int main()
{
    int n = 2500;
 
    // Function Call
    if (n == 0 || isPerfectSquare(n))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}


Java




// Java program for above approach
class 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 (x == 0 || isPerfectSquare(x))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}


Python3




# 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 code
if __name__ == "__main__":
   
  x = 2500
   
  # Function Call
  if x == 0:
        print("Yes, it is a perfect square.")
  elif (isPerfectSquare(x)):
      print("Yes")
  else:
      print("No")


C#




// C# program for above approach
using 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 code
public static void Main(string[] args)
{
  int n = 2500;
 
  // Function Call
  if (n == 0 || isPerfectSquare(n))
    Console.Write("Yes");
  else
    Console.Write("No");
}
}
 
// This code is contributed by Rutvik_56n == 0 ||


Javascript




<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 Code
let x = 2500;
 
// Function Call
if (x == 0 || isPerfectSquare(x))
    document.write("Yes");
else
    document.write("Yes");
     
// This code is contributed by rishavmahato348
 
</script>


Output

Yes

Time Complexity : O(log(N))
Auxiliary Space: O(1) 

Method 3: Using the property that the sum of odd numbers is a perfect square

The given program checks if a number is a perfect square without finding the square root. It does this by iterating over the odd numbers, starting from 1 and subtracting them from the given number n. If n becomes zero, it means that n is a perfect square.

C++




#include <iostream>
using namespace std;
 
bool is_perfect_square(int n) {
    int i = 1;
    while (n > 0) {
        n -= i;
        i += 2;
    }
    return n == 0;
}
 
int main() {
    int n = 36;
    if (is_perfect_square(n)) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
 
    n = 12;
    if (is_perfect_square(n)) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
 
    return 0;
}


Java




// Java program for the above approach
public class GFG {
    public static boolean isPerfectSquare(int n) {
        int i = 1;
        while (n > 0) {
            n -= i;
            i += 2;
        }
        return n == 0;
    }
 
    public static void main(String[] args) {
        int n = 36;
        if (isPerfectSquare(n)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
 
        n = 12;
        if (isPerfectSquare(n)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by Prince Kumar


Python3




def is_perfect_square(n):
    i = 1
    while n > 0:
        n -= i
        i += 2
    return n == 0
 
n = 36
if is_perfect_square(n):
    print("Yes")
else:
    print("No")
 
n = 12
if is_perfect_square(n):
    print("Yes")
else:
    print("No")


C#




using System;
 
class Program {
    static bool IsPerfectSquare(int n)
    {
        int i = 1;
        while (n > 0) {
            n -= i;
            i += 2;
        }
        return n == 0;
    }
 
    static void Main(string[] args)
    {
        int n = 36;
        if (IsPerfectSquare(n)) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
 
        n = 12;
        if (IsPerfectSquare(n)) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}


Javascript




function is_perfect_square(n) {
    let i = 1;
    while (n > 0) {
        n -= i;
        i += 2;
    }
    return n === 0;
}
 
let n = 36;
if (is_perfect_square(n)) {
    console.log("Yes");
}
else {
    console.log("No");
}
 
n = 12;
if (is_perfect_square(n)) {
    console.log("Yes");
}
else {
    console.log("No");
}


Output

Yes
No

Time complexity: O(sqrt(n)) since it takes at most sqrt(n) iterations to check if a number is a perfect square.
Auxiliary space: O(1).



Similar Reads

Check if a number is a perfect square having all its digits as a perfect square
Given an integer N, the task is to check if the given number is a perfect square having all its digits as a perfect square or not. If found to be true, then print “Yes”. Otherwise, print “No”.Examples: Input: N = 144 Output: Yes Explanation: The number 144 is a perfect square and also the digits of the number {1(= 12, 4(= 22} is also a perfect squa
11 min read
Find smallest perfect square number A such that N + A is also a perfect square number
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.Examples: Input: N = 3 Output: 1 Explanation: As 1 + 3 = 4 = 22 Input: N=1 Output: -1 Naive Approach: Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
9 min read
Print middle level of perfect binary tree without finding height
Given a perfect binary tree, print nodes of middle level without computing its height. A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level. Output : 4 5 6 7 The idea is similar to method 2 of finding middle of singly linked list.Use fast and slow (or tortoise) pointer
7 min read
Finding the Missing Digit in the Largest Perfect Square
Given a perfect square number with one missing digit represented by an underscore (_). Find the missing digit that when inserted, creates the largest perfect square. Examples: Input: "14_"Output: 4Explanation: The missing digit 4 makes the largest perfect square, 144. Input: 6_25Output: 1Explanation: The missing digit 1 makes the largest perfect sq
5 min read
Count numbers upto N which are both perfect square and perfect cube
Given a number N. The task is to count total numbers under N which are both perfect square and cube of some integers.Examples: Input: N = 100Output: 2They are 1 and 64.Input: N = 100000Output: 6Naive Approach: The idea is to use the power, square_root and cube_root functions from the math library. C/C++ Code // C++ program for the above approach #i
5 min read
Square root of a number without using sqrt() function
Given a number N, the task is to find the square root of N without using sqrt() function. Examples: Input: N = 25 Output: 5 Input: N = 3 Output: 1.73205 Input: N = 2.5 Output: 1.58114 Approach 1: We can consider (?x-?x)2 = 0.Replacing one of the ?x's with y, then the equation becomes (y-?x)2 =&gt; y2 - 2y?x + x = 0=&gt; ?x = (y2 + x) / 2y=&gt; ?x =
14 min read
Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Smallest N digit number whose sum of square of digits is a Perfect Square
Given an integer N, find the smallest N digit number such that the sum of the square of digits (in decimal representation) of the number is also a perfect square. If no such number exists, print -1.Examples: Input : N = 2 Output : 34 Explanation: The smallest possible 2 digit number whose sum of square of digits is a perfect square is 34 because 32
15+ min read
Why do we check up to the square root of a number to determine if that number is Prime?
Why do we check up to the square root of a number to determine if that number is prime?Prime numbers are natural numbers greater than 1 which are divisible only by 1 and itself. Examples include 2, 3, 5, 7, 11, 13, etc. (1 is neither prime nor composite). Here is the code to check whether a number is prime or not. As, the loop checks for each numbe
3 min read
Print all Perfect Numbers from an array whose sum of digits is also a Perfect Number
Given an array arr[] of size N, the task is to print all the perfect numbers from an array whose sum of digits is also a perfect number. Examples: Input: arr[] = { 3, 8, 12, 28, 6 }Output: 6Explanation: The array element arr[4] (= 6) is a perfect number. The array element arr[3] (= 28) is a perfect number but its sum of digits (= 10) is not a perfe
8 min read
Floor square root without using sqrt() function : Recursive
Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root. Examples: Input: N = 25 Output: 5 Explanation: Square root of 25 = 5. Therefore 5 is the greatest whole number less th
7 min read
Check whether the number formed by concatenating two numbers is a perfect square or not
Given two numbers a and b and the task is to check whether the concatenation of a and b is a perfect square or not.Examples: Input: a = 1, b = 21 Output: Yes 121 = 11 × 11, is a perfect square. Input: a = 100, b = 100 Output: No 100100 is not a perfect square. Approach: Initialize the number as strings initially and concatenate them. Convert the st
4 min read
Check whether the number can be made perfect square after adding K
Given two numbers N and K, the task is to check whether the given number N can be made a perfect square after adding K to it.Examples: Input: N = 7, K = 2 Output: Yes Explanation: 7 + 2 = 9 which is a perfect square. Input: N = 5, K = 3 Output: No Explanation: 5 + 3 = 8 which is not a perfect square. Approach: The idea is to compute the value of N
4 min read
Count of pair of integers (x , y) such that difference between square of x and y is a perfect square
Given an integer N. The task is to find the number of pairs of integers (x, y) both less than N and greater than 1, such that x2 - y is a square number or 0. Example: Input: N = 3Output: 2Explanation:The only possible valid pairs are (1, 1), (2, 3). Therefore, the count of such pairs is 2. Input: N = 2Output: 1 Naive Approach: The simplest approach
11 min read
Count integers whose square lie in given range and digits are perfect square
Given two integers L and R. Then the task is to output the count of integers X, such that L â‰Ī X2 â‰Ī R and X2 only consist of digits, which are perfect squares. Examples: Input: L = 167, R = 456Output: 2Explanation: Two numbers are 20 and 21, Their squares are 400 and 441 respectively. It can be verified that squares of both 20 and 21 are in the rang
13 min read
Finding the Missing digit in the Largest Perfect Cube
Given a perfect cube number with one missing digit represented by an underscore _, the task is to find the missing digit that when inserted, creates the largest perfect cube. Examples: Input: "219_"Output: 7Explanation: The missing digit 7 makes the largest perfect cube, 2197. Input: 15_25Output: 6Explanation: The missing digit 6 makes the largest
4 min read
Number of times the largest perfect square number can be subtracted from N
Given a number N. At every step, subtract the largest perfect square( ? N) from N. Repeat this step while N &gt; 0. The task is to count the number of steps that can be performed. Examples: Input: N = 85 Output: 2 First step, 85 - (9 * 9) = 4 Second step 4 - (2 * 2) = 0 Input: N = 114 Output: 4 First step, 114 - (10 * 10) = 14 Second step 14 - (3 *
7 min read
Previous perfect square and cube number smaller than number N
Given an integer N, the task is to find the previous perfect square or perfect cube smaller than the number N.Examples: Input: N = 6 Output: Perfect Square = 4 Perfect Cube = 1 Input: N = 30 Output: Perfect Square = 25 Perfect Cube = 27 Approach: Previous perfect square number less than N can be computed as follows: Find the square root of given nu
5 min read
Find minimum number to be divided to make a number a perfect square
Given a positive integer n. Find the minimum number which divide n to make it a perfect square.Examples: Input : n = 50 Output : 2 By Dividing n by 2, we get which is a perfect square. Input : n = 6 Output : 6 By Dividing n by 6, we get which is a perfect square. Input : n = 36 Output : 1 A number is perfect square if all prime factors appear even
7 min read
Check if the Product of all Array elements is a Perfect Square or not
Given an array arr[] consisting of N positive integers, the task is to check if the product of all the elements of the given array arr[] is a perfect square or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: arr[] = {1, 4, 100}Output: YesExplanation: The product of all the numbers is 1 x 4 x 100 = 400 which is a perf
6 min read
Check if product of array containing prime numbers is a perfect square
Given an array arr[] containing only prime numbers, the task is to check if the product of the array elements is a perfect square or not.Examples: Input: arr[] = {2, 2, 7, 7} Output: Yes 2 * 2 * 7 * 7 = 196 = 142Input: arr[] = {3, 3, 3, 5, 5} Output: No Naive approach: Multiply all the elements of the array and check whether the product is a perfec
4 min read
Check if the sum of a subarray within a given range is a perfect square or not
Given an array arr[] of size N and an array range[], the task is to check if the sum of the subarray {range[0], .. , range[1]} is a perfect square or not. If the sum is a perfect square, then print the square root of the sum. Otherwise, print -1. Example : Input: arr[] = {2, 19, 33, 48, 90, 100}, range = [1, 3] Output: 10 Explanation: The sum of el
7 min read
Check whether the product of every subsequence is a perfect square or not
Given an array arr[] consisting of N positive integers, the task is to check if the product of elements of every subsequence of the given array arr[] is a perfect square or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: arr[] = {1, 4, 100}Output: YesExplanation:Following are the subsequences of the given array arr[]
5 min read
Check perfect square using addition/subtraction
Given a positive integer n, check if it is perfect square or not using only addition/subtraction operations and in minimum time complexity.We strongly recommend you to minimize your browser and try this yourself first.We can use the property of odd number for this purpose: Addition of first n odd numbers is always perfect square 1 + 3 = 4, 1 + 3 +
4 min read
Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x.
You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x - n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 &lt;= N &lt;= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x
8 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a number x such that (x*x)%7 is 2. The number is 3.
11 min read
Minimum digits to remove to make a number Perfect Square
Given an integer n, we need to find how many digits remove from the number to make it a perfect square. Examples : Input : 8314 Output: 81 2 Explanation: If we remove 3 and 4 number becomes 81 which is a perfect square. Input : 57 Output : -1 The idea is to generate all possible subsequences and return the optimal string using set bits. Let's suppo
9 min read
Largest perfect square number in an Array
Given an array of n integers. The task is to find the largest number which is a perfect square. Print -1 if there is no number that is perfect square.Examples: Input : arr[] = {16, 20, 25, 2, 3, 10} Output : 25 Explanation: 25 is the largest number that is a perfect square. Input : arr[] = {36, 64, 10, 16, 29, 25| Output : 64 A Simple Solution is t
8 min read
Largest Divisor of a Number not divisible by a perfect square
Given a positive integer, N. Find the largest divisor of the given number that is not divisible by a perfect square greater than 1. Examples: Input : 12 Output : 6 Explanation : Divisors of 12 are 1, 2, 3, 4, 6 and 12. Since 12 is divisible by 4 (a perfect square), it can't be required divisor. 6 is not divisible by any perfect square. Input :97 Ou
12 min read