Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 the square of a number is divisible by K or not
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 the square of a number is divisible by K or not

A

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

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 the square of a number is divisible by K or not
    Given two integers, X and K, the task is to find if X2 is divisible by K or not. Here, both K and X can lie in the range [1,1018]. Examples: Input: X = 6, K = 9 Output: YES Explanation: Since 62 is equal to 36, which is divisible by 9. Input: X = 7, K = 21 Output: NO Explanation: Since 72 is equal t
    4 min read
  • C++ Program To Check And Print Neon Number in a Given Range
    A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range. Examples: Input: 9 Output: Neon Number Explanation: square is 9*9 = 81 and sum of the digits of the square is 9. Input: 12 Output: Not a Neon
    2 min read
  • C++ Program for How to check if a given number is Fibonacci number?
    Given a number 'n', how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : Input : 8 Output : Yes Input : 34 Output : Yes Input : 41 Output : No Following is an interesting property about Fibonacci numbers that can also be
    2 min read
  • Check if all Prime factors of number N are unique or not
    Given a number N. The task is to check whether the given number N has unique prime factors or not. If yes then print YES else print NO.Examples: Input: N = 30 Output: YES Explanation: N = 30 = 2*3*5 As all the prime factors of 30 are unique.Input: N = 100 Output: NO Explanation: N = 100 = 2*2*5*5 As
    8 min read
  • Check if a large number is divisible by a number which is a power of 2
    Given a large number in the form of a string str and a number K, the task is to check if the number formed by string str is divisible by the K or not, where K is a power of 2. Examples: Input: str = "5426987513245621541524288", num = 64 Output: Yes Explanation: Since log2(64) = 6, so the number form
    7 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
  • Find pairs of elements from two different arrays whose product is a perfect square
    Prerequisites: Prime Factorization using SieveGiven two arrays arr1[] and arr2[] of size M and N with distinct elements in each of the arrays, the task is to find those pair of elements (one from the first array and other from the second array) whose product is a perfect square. Print -1 if no pairs
    15+ min read
  • Sum of the digits of square of the given number which has only 1's as its digits
    Given a number represented as string str consisting of the digit 1 only i.e. 1, 11, 111, .... The task is to find the sum of digits of the square of the given number. Examples: Input: str = 11 Output: 4 112 = 121 1 + 2 + 1 = 4 Input: str = 1111 Output: 16 Naive approach: Find the square of the given
    6 min read
  • Lagrange's four square theorem
    Lagrange's Four Square Theorem states that every natural number can be written as sum of squares of four non negative integers. For eg. [Tex]1 = 0^2 + 0^2 + 0^2 +1^2 [/Tex]Similarly [Tex]2 = 0^2 + 0^2 + 1^2 +1^2 [/Tex]Similarly for any [Tex]n\in N, n = a^2 + b^2 + c^2 + d^2 where \ a, b, c, d, \in N
    8 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