Check Perfect Square or Not

Data StructureMisc AlgorithmsAlgorithms

A number is said to be a perfect square number if the square root of that number is an integer. In other words, when a square root is a whole number, then the number is called a perfect square number.

We can check perfect square by finding the square root of that number and match with i again and again to get exact square root. When the square root crosses the value, it is not a perfect square number.

But here to reduce effort, we have not checked the square root again and again. As we know that the square root of a perfect square number is an integer, then we can increase the square root by one, and check for a perfect square match.

Input and Output

Input: 
A number to check: 1032
Output: 
1032 is not a perfect square number.

Algorithm

isPerfectSquare(num)

Input: The number.

Output: True if a number is the perfect square number, and also print the square root.

Begin
   if num < 0, then
      exit
   sqRoot := 1
   sq := sqRoot^2
   while sq <= num, do
      if sq = num, then
         return sqRoot
      sqRoot := sqRoot + 1
      sq := sqRoot^2
   done
   otherwise return error
End

Source Code (C++)

#include<iostream>
using namespace std;

int isPerfectSquare(int num) {
   if(num < 0)
      return -1;            //a -ve number is not a valid square term
   int sqRoot = 1, sq;

   while((sq =(sqRoot*sqRoot)) <= num) {             //when square of square root is not crossed the number
      if(sq == num)
         return sqRoot;
      sqRoot++;               //as square root of a perfect square is always integer
   }
   return -1;
}

int main() {
   int num, res;
   cout << "Enter a number to check whether it is perfect square or not: ";
   cin >> num;

   if((res = isPerfectSquare(num)) != -1)
      cout << num << " is a perfect square number, square root: " << res;
   else
      cout << num << " is not a perfect square number.";
}

Output

Enter a number to check whether it is perfect square or not: 1032
1032 is not a perfect square number.
raja
Published on 12-Jul-2018 07:41:51
Advertisements