C++ Exercises: Check whether a given positive integer is a perfect square or not
C++ Math: Exercise-30 with Solution
Write a C++ program to check whether a given positive integer is a perfect square or not.
In mathematics, a square number or perfect square is an integer that is the square of an integer, in other words, it is the product of some integer with itself. For example, 9 is a square number, since it can be written as 3 × 3.
Sample Input: n = 1
Is 1 is perfect number? 1
Sample Input: n = 13
Is 13 is perfect number? 0
Sample Solution:
C++ Code :
#include <iostream>
#include <cmath>
using namespace std;
bool is_Perfect_Square(int num) {
long long start_num = 0;
long long end_num = num;
while(start_num + 1 < end_num)
{
long long mid_num = start_num + (end_num - start_num) / 2;
if (mid_num * mid_num < num)
{
start_num = mid_num;
}
else if(mid_num * mid_num > num)
{
end_num = mid_num;
}
else
{
return true;
}
}
return start_num * start_num == num || end_num * end_num == num;
}
int main()
{
int n = 1;
cout << "\nIs "<< n << " is perfect number? " << is_Perfect_Square(n) << endl;
n = 13;
cout << "\nIs "<< n << " is perfect number? " << is_Perfect_Square(n) << endl;
n = 16;
cout << "\nIs "<< n << " is perfect number? " << is_Perfect_Square(n) << endl;
n = 125;
cout << "\nIs "<< n << " is perfect number? " << is_Perfect_Square(n) << endl;
return 0;
}
Sample Output:
Is 1 is perfect number? 1 Is 13 is perfect number? 0 Is 16 is perfect number? 1 Is 125 is perfect number? 0
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to count all the numbers with unique digits within a given range 0 ≤ y < 10n where y represent the unique digits numbers and take n as a input from the user.
Next: Write a C++ program to replace a given number until it become 1.
What is the difficulty level of this exercise?