This can be implemented in two ways: one by looping till half the number and check if at each iteration multiplying the counter with itself results in the number.
public static bool IsPerfectSquare(int n)
{
for (int i = 1; i <= n / 2; i++)
{
if (i * i == n)
{
return true;
}
}
return false;
}
Or by using the Math library and find the square root of the number. Then see if the obtained square root is an integer or not.
public static bool IsPerfectSquareBySqRoot(int n)
{
double root = Math.Sqrt(n);
if (root - Math.Floor(root) == 0)
{
return true;
}
return false;
}