Suppose a number is given, we have to check whether the number is a perfect square or not. We will not use the square root operation to check it. Suppose a number 1024 is there, this is a perfect square, but 1000 is not a perfect square. The logic is simple, we have to follow this algorithm to get the result.
Algorithm
isPerfectSquare(n) −
input − The number n
output − true, if the number is a perfect square, otherwise, false
begin for i := 1, i2 ≤ n, increase i by 1: if n is divisible by i, and n / i = i, then return true done return false end
Example
#include <iostream>
using namespace std;
bool isPerfectSquare(int number) {
for (int i = 1; i * i <= number; i++) {
if ((number % i == 0) && (number / i == i)) {
return true;
}
}
return false;
}
int main() {
int n = 1024;
if(isPerfectSquare(n)){
cout << n << " is perfect square number";
} else {
cout << n << " is not a perfect square number";
}
}Output
1024 is perfect square number