Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Check if given number is perfect square
Next article icon

Check if given number is perfect square

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a number n, check if it is a perfect square or not. 

Examples : 

Input : n = 36
Output : Yes

Input : n = 2500
Output : Yes
Explanation: 2500 is a perfect square of 50

Input : n = 8
Output : No

Table of Content

  • Using sqrt()
  • Using ceil, floor and sqrt() functions
  • Using Binary search
  • Using Mathematical Properties

Using sqrt()

  • Take the floor()ed square root of the number.
  • Multiply the square root twice.
  • Use boolean equal operator to verify if the product of square root is equal to the number given.

Code Implementation:

C++
// CPP program to find if x is a // perfect square. #include <bits/stdc++.h> using namespace std;  bool isPerfectSquare(long long x) {     // Find floating point value of     // square root of x.     if (x >= 0) {          long long sr = sqrt(x);                  // if product of square root          //is equal, then         // return T/F         return (sr * sr == x);     }     // else return false if n<0     return false; }  int main() {     long long x = 49;     if (isPerfectSquare(x))         cout << "Yes";     else         cout << "No";     return 0; } 
C
// C program to find if x is a // perfect square. #include <stdio.h> #include <math.h>  int isPerfectSquare(long long x) {     // Find floating point value of     // square root of x.     if (x >= 0) {         long long sr = sqrt(x);          // if product of square root         // is equal, then         // return T/F         return (sr * sr == x);     }     // else return false if n<0     return 0; }  int main() {     long long x = 49;     if (isPerfectSquare(x))         printf("Yes");     else         printf("No");     return 0; } 
Java
// Java program to find if x is a perfect square. public class GfG {      public static boolean isPerfectSquare(long x)     {         // Find floating point value of         // square root of x.         if (x >= 0) {             long sr = (long)Math.sqrt(x);              // if product of square root             // is equal, then             // return T/F             return (sr * sr == x);         }         // else return false if n<0         return false;     }      public static void main(String[] args)     {         long x = 49;         if (isPerfectSquare(x))             System.out.println("Yes");         else             System.out.println("No");     } } 
Python
# Python program to find if x is a # perfect square. def is_perfect_square(x):     # Find floating point value of     # square root of x.     if x >= 0:         sr = int(x ** 0.5)          # if product of square root         # is equal, then         # return T/F         return (sr * sr == x)     # else return false if n<0     return False  x = 49 if is_perfect_square(x):     print("Yes") else:     print("No") 
C#
// C# program to find if x is a // perfect square. using System;  class GfG {     static bool IsPerfectSquare(long x) {         // Find floating point value of         // square root of x.         if (x >= 0) {             long sr = (long) Math.Sqrt(x);              // if product of square root             // is equal, then             // return T/F             return (sr * sr == x);         }         // else return false if n<0         return false;     }      static void Main() {         long x = 49;         if (IsPerfectSquare(x))             Console.WriteLine("Yes");         else             Console.WriteLine("No");     } } 
JavaScript
// JavaScript program to find if x is a // perfect square. function isPerfectSquare(x) {     // Find floating point value of     // square root of x.     if (x >= 0) {         let sr = Math.floor(Math.sqrt(x));          // if product of square root         // is equal, then         // return T/F         return (sr * sr === x);     }     // else return false if n<0     return false; }  const x = 49; if (isPerfectSquare(x))     console.log("Yes"); else     console.log("No"); 

Output
Yes

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

Using ceil, floor and sqrt() functions

  • Use the floor and ceil and sqrt() function.
  • If they are equal that implies the number is a perfect square.

Code Implementation:

C++
#include <bits/stdc++.h> using namespace std;  bool isPerfectSquare(long long n) {     // If ceil and floor are equal     // the number is a perfect     // square     if (ceil((double)sqrt(n)) == floor((double)sqrt(n))){         return true;     }     else{         return false;     } }  int main() {     long long x = 49;     if (isPerfectSquare(x))         cout << "Yes";     else         cout << "No";     return 0; } 
C
#include <stdio.h> #include <math.h>  // If ceil and floor are equal // the number is a perfect // square int isPerfectSquare(long long n) {     if (ceil((double)sqrt(n)) == floor((double)sqrt(n))) {         return 1;  // true     }     else {         return 0;  // false     } }  int main() {     long long x = 49;     if (isPerfectSquare(x))         printf("Yes");     else         printf("No");     return 0; } 
Java
public class GfG {     public static boolean isPerfectSquare(long n) {         // If ceil and floor are equal         // the number is a perfect         // square         if (Math.ceil(Math.sqrt(n)) == Math.floor(Math.sqrt(n))) {             return true;         } else {             return false;         }     }      public static void main(String[] args) {         long x = 49;         if (isPerfectSquare(x))             System.out.println("Yes");         else             System.out.println("No");     } } 
Python
import math  def is_perfect_square(n):     # If ceil and floor are equal     # the number is a perfect     # square     if math.ceil(math.sqrt(n)) == math.floor(math.sqrt(n)):         return True     else:         return False  x = 49 if is_perfect_square(x):     print("Yes") else:     print("No") 
C#
using System;  class GfG {     public static bool IsPerfectSquare(long n) {         // If ceil and floor are equal         // the number is a perfect         // square         if (Math.Ceiling(Math.Sqrt(n)) == Math.Floor(Math.Sqrt(n))) {             return true;         } else {             return false;         }     }      static void Main() {         long x = 49;         if (IsPerfectSquare(x))             Console.WriteLine("Yes");         else             Console.WriteLine("No");     } } 
JavaScript
function isPerfectSquare(n) {     // If ceil and floor are equal     // the number is a perfect     // square     if (Math.ceil(Math.sqrt(n)) === Math.floor(Math.sqrt(n))) {         return true;     } else {         return false;     } }  const x = 49; if (isPerfectSquare(x)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes

Time Complexity : O(sqrt(n))
Auxiliary space: O(1)

Using Binary search:

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h> using namespace std;  // Function to check if a number is a perfect square using // binary search bool isPerfectSquare(long long n) {     // Base case: 0 and 1 are perfect squares     if (n <= 1) {         return true;     }      // Initialize boundaries for binary search     long long left = 1, right = n;      while (left <= right) {          // Calculate middle value         long long mid = left + (right - left) / 2;          // Calculate square of the middle value         long long square = mid * mid;          // If the square matches n, n is a perfect square         if (square == n) {             return true;         }          // If the square is smaller than n, search the right         // half         else if (square < n) {              left = mid + 1;         }          // If the square is larger than n, search the left         // half         else {              right = mid - 1;         }     }      // If the loop completes without finding a perfect     // square, n is not a perfect square     return false; }  int main() {     long long x = 49;     if (isPerfectSquare(x))         cout << "Yes";     else         cout << "No";     return 0; } 
C
#include <stdio.h>  // Function to check if a number is a perfect square using // binary search int isPerfectSquare(long long n) {     // Base case: 0 and 1 are perfect squares     if (n <= 1) {         return 1;     }      // Initialize boundaries for binary search     long long left = 1, right = n;      while (left <= right) {         // Calculate middle value         long long mid = left + (right - left) / 2;          // Calculate square of the middle value         long long square = mid * mid;          // If the square matches n, n is a perfect square         if (square == n) {             return 1;         }         // If the square is smaller than n, search the right half         else if (square < n) {             left = mid + 1;         }         // If the square is larger than n, search the left half         else {             right = mid - 1;         }     }      // If the loop completes without finding a perfect square, n is not a perfect square     return 0; }  int main() {     long long x = 49;     if (isPerfectSquare(x))         printf("Yes");     else         printf("No");     return 0; } 
Java
public class GfG {     // Function to check if a number is a perfect square using     // binary search     public static boolean isPerfectSquare(long n) {         // Base case: 0 and 1 are perfect squares         if (n <= 1) {             return true;         }          // Initialize boundaries for binary search         long left = 1, right = n;          while (left <= right) {             // Calculate middle value             long mid = left + (right - left) / 2;              // Calculate square of the middle value             long square = mid * mid;              // If the square matches n, n is a perfect square             if (square == n) {                 return true;             }             // If the square is smaller than n, search the right             // half             else if (square < n) {                 left = mid + 1;             }             // If the square is larger than n, search the left             // half             else {                 right = mid - 1;             }         }          // If the loop completes without finding a perfect         // square, n is not a perfect square         return false;     }      public static void main(String[] args) {         long x = 49;         if (isPerfectSquare(x))             System.out.println("Yes");         else             System.out.println("No");     } } 
Python
def is_perfect_square(n):     # Base case: 0 and 1 are perfect squares     if n <= 1:         return True      # Initialize boundaries for binary search     left, right = 1, n      while left <= right:         # Calculate middle value         mid = left + (right - left) // 2          # Calculate square of the middle value         square = mid * mid          # If the square matches n, n is a perfect square         if square == n:             return True         # If the square is smaller than n, search the right half         elif square < n:             left = mid + 1         # If the square is larger than n, search the left half         else:             right = mid - 1      # If the loop completes without finding a perfect square, n is not a perfect square     return False  x = 49 if is_perfect_square(x):     print("Yes") else:     print("No") 
C#
using System;  class GfG {     // Function to check if a number is a perfect square using     // binary search     static bool IsPerfectSquare(long n) {         // Base case: 0 and 1 are perfect squares         if (n <= 1) {             return true;         }          // Initialize boundaries for binary search         long left = 1, right = n;          while (left <= right) {             // Calculate middle value             long mid = left + (right - left) / 2;              // Calculate square of the middle value             long square = mid * mid;              // If the square matches n, n is a perfect square             if (square == n) {                 return true;             }             // If the square is smaller than n, search the right half             else if (square < n) {                 left = mid + 1;             }             // If the square is larger than n, search the left half             else {                 right = mid - 1;             }         }          // If the loop completes without finding a perfect square, n is not a perfect square         return false;     }      static void Main() {         long x = 49;         if (IsPerfectSquare(x))             Console.WriteLine("Yes");         else             Console.WriteLine("No");     } } 
JavaScript
function isPerfectSquare(n) {     // Base case: 0 and 1 are perfect squares     if (n <= 1) {         return true;     }      // Initialize boundaries for binary search     let left = 1, right = n;      while (left <= right) {         // Calculate middle value         let mid = left + Math.floor((right - left) / 2);          // Calculate square of the middle value         let square = mid * mid;          // If the square matches n, n is a perfect square         if (square === n) {             return true;         }         // If the square is smaller than n, search the right half         else if (square < n) {             left = mid + 1;         }         // If the square is larger than n, search the left half         else {             right = mid - 1;         }     }      // If the loop completes without finding a perfect square, n is not a perfect square     return false; }  const x = 49; if (isPerfectSquare(x)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes

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

Using Mathematical Properties:

The idea is based on the fact that perfect squares are always some of first few odd numbers.

1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
1 + 3 + 5 + 7 + 9 = 25
1 + 3 + 5 + 7 + 9 + 11 = 36
......................................................

Code Implementation:

C++
#include <bits/stdc++.h> using namespace std;  bool isPerfectSquare(long long n) {        // 0 is considered as a perfect     // square     if (n == 0) return true; 	     long long odd = 1; 	while (n > 0) { 		n -= odd; 		odd += 2; 	} 	return n == 0; }  int main() {     long long x = 49;     if (isPerfectSquare(x))         cout << "Yes";     else         cout << "No";     return 0; } 
C
#include <stdio.h>  // 0 is considered as a perfect // square int isPerfectSquare(long long n) {     if (n == 0) return 1; // true      long long odd = 1;     while (n > 0) {         n -= odd;         odd += 2;     }     return n == 0; }  int main() {     long long x = 49;     if (isPerfectSquare(x))         printf("Yes");     else         printf("No");     return 0; } 
Java
public class GfG {     public static boolean isPerfectSquare(long n) {         // 0 is considered as a perfect         // square         if (n == 0) return true;          long odd = 1;         while (n > 0) {             n -= odd;             odd += 2;         }         return n == 0;     }      public static void main(String[] args) {         long x = 49;         if (isPerfectSquare(x))             System.out.println("Yes");         else             System.out.println("No");     } } 
Python
def is_perfect_square(n):     # 0 is considered as a perfect     # square     if n == 0:         return True      odd = 1     while n > 0:         n -= odd         odd += 2     return n == 0  x = 49 if is_perfect_square(x):     print("Yes") else:     print("No") 
C#
using System;  class GfG {     public static bool IsPerfectSquare(long n) {         // 0 is considered as a perfect         // square         if (n == 0) return true;          long odd = 1;         while (n > 0) {             n -= odd;             odd += 2;         }         return n == 0;     }      static void Main() {         long x = 49;         if (IsPerfectSquare(x))             Console.WriteLine("Yes");         else             Console.WriteLine("No");     } } 
JavaScript
function isPerfectSquare(n) {     // 0 is considered as a perfect     // square     if (n === 0) return true;      let odd = 1;     while (n > 0) {         n -= odd;         odd += 2;     }     return n === 0; }  const x = 49; if (isPerfectSquare(x)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes

How does this work?

1 + 3 + 5 + ... (2n-1) = Sum(2*i - 1) where 1<=i<=n
= 2*Sum(i) - Sum(1) where 1<=i<=n
= 2n(n+1)/2 - n
= n(n+1) - n
= n2'

Time Complexity Analysis

Let us assume that the above loop runs i times. The following series would have i terms.

1 + 3 + 5 ........ = n [Let there be i terms]
1 + (1 + 2) + (1 + 2 + 2) + ........ = n [Let there be i terms]
(1 + 1 + ..... i-times) + (2 + 4 + 6 .... (i-1)-times) = n
i + (2^(i-1) - 1) = n
2^(i-1) = n + 1 - i
Using this expression, we can say that i is upper bounded by Log n


Next Article
Check if given number is perfect square

A

Aditya Darekar
Improve
Article Tags :
  • Misc
  • Mathematical
  • C++ Programs
  • DSA
  • maths-perfect-square
Practice Tags :
  • Mathematical
  • Misc

Similar Reads

    Check if a given number is a Perfect square using Binary Search
    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: 9 Explanation: 81 is a perfect squar
    6 min read
    Check if a number can be represented as a sum of a Prime Number and a Perfect Square
    Given a positive integer N, the task is to check if N can be represented as a sum of a Prime Number and a Perfect Square or not. If it is possible to represent N in required form, then print "Yes". Otherwise, print "No". Examples: Input: N = 27Output: YesExplanation: 27 can be expressed as sum of 2
    15+ min read
    Check if a number is perfect square without finding square root
    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 PracticeCheck perfect squareTry It! 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
    9 min read
    PHP | Check if a number is Perfect number
    A perfect number is a number if it is equal to the sum of its factors,that is original number is equal to sum of all its factors excluding the number itself. We have already discuss how to check if a number is perfect or not in this article. In this article we will discuss about how to do the same i
    2 min read
    Largest factor of a given number which is a perfect square
    Given a number N . The task is to find the largest factor of that number which is a perfect square.Examples: Input : N = 420Output : 4Input : N = 100Output : 100A Simple Solution is to traverse all of the numbers in decreasing order from the given number down till 1 and if any of these numbers is a
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences