Program to Check for Perfect Square in C++

Check for Perfect Square in C++

Today in this article we will discuss the program to check for perfect square in C++ programming language. We are given with an integer number and need to print “True” if it is, otherwise “False”.

TCS ITP Eligibility Criteria

Method 1:

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

Method 1 :Code in C++

Run
#include <bits/stdc++.h>
using namespace std;
 
bool isPerfectSquare(long double x)
{
    if (x >= 0) {
 
        long long sr = sqrt(x);
        return (sr * sr == x);
    }
    
    return false;
}
 
int main()
{
    long long x = 84;
    if (isPerfectSquare(x))
        cout << "True";
    else
        cout << "False";
    return 0;
}

Output :

False

Method 2 :

  • In this method we use the floor and ceil function .
  • If they are equal that implies the number is a perfect square.
Check for Perfect Square or Not in C++

Method 2 :Code in C++

Run
#include <iostream>
#include <math.h>
using namespace std;
 
void checkperfectsquare(int n)
{
    if (ceil((double)sqrt(n)) == floor((double)sqrt(n))) {
        cout << "True";
    }
    else {
        cout << "False";
    }
}

int main()
{
 
    int n = 49;
    checkperfectsquare(n);
    return 0;
}

Output :

True

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

One comment on “Program to Check for Perfect Square in C++”


  • sudhanshu

    // perfect square

    #include
    #include
    #include
    using namespace std;

    void perfect(int n){
    int square, temp = n, digit;
    for (int i = 1; i < n; i++)
    {
    square = pow(i,2);
    if(square == temp)
    break;
    digit = i+1;
    }
    square == temp? cout<<square<<" is a Perfect square of "<<digit:cout<<"Not a perfect square";

    }

    int main()
    {
    int num;
    cout<> num;
    perfect(num);
    return 0;
    }