Visual C++ - Check Perfect Square
Write a Program to check whether a num is perfect square or not, 25, 36, 49 are perfect squares.
The idea here is to find out the square root of given number and convert it into an integer and do the square to check whether it is a perfect square or NOT. If the number falls between the square of min and square of max, then it is not a perfect square.
Look at the sample code and output.
Source Code
#include <stdio.h>
#include <iostream>
#include <tchar.h>
#include <math.h>
int CheckPerfectSquare(int num)
{
int min = 0, max = 1000;
int answer = 0;
int test = 0;
while(1)
{
test = (min + max) / 2;
answer = test * test;
if( num > answer)
{
// min needs be moved
min = test;
}
else if(num < answer)
{
// max needs be moved
max = test;
}
if(num == answer)
{
std::cout << "\n" << num << " is a perfect square of " << test;
return 1; // perfect square
}
if((max - min) <= 1)
{
std::cout << "\n" << num << " is NOT a perfect square";
return 0; // Not a perfect square
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
CheckPerfectSquare(25);
CheckPerfectSquare(36);
CheckPerfectSquare(49);
CheckPerfectSquare(64);
CheckPerfectSquare(68);
CheckPerfectSquare(127);
std::cout << "\n";
return 0;
}
Output
25 is a perfect square of 5
36 is a perfect square of 6
49 is a perfect square of 7
64 is a perfect square of 8
68 is NOT a perfect square
127 is NOT a perfect square
|