Check if given number is perfect square
Last Updated :
17 Sep, 2024
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
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");
Time Complexity: O(log(x))
Auxiliary Space: O(1)
- 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");
}
Time Complexity : O(sqrt(n))
Auxiliary space: O(1)
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");
}
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");
}
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
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read