How to find if the number is a Perfect Square

In this coding problem, for any given number, we need to find if there is a number which multiplied by itself results in the same number.

What is a Perfect Square?

A Perfect square is a whole number which is produced by multiplying two equal integers. In other words, a number which has a square root as an integer is called a Perfect square.

Examples are 1, 4, 9, 25, .. and such.

How to find if the given number is a Perfect Square

This can be implemented in two ways: one by looping till half the number and checking if at each iteration multiplying the counter with itself results in the number.

public class CodingProblemSolution
{
    public static bool IsPerfectSquare(int n)
    {
        for (int i = 1; i <= n / 2; i++)
        {
            if (i * i == n)
            {
                return true;
            }
        }


        return false;
    }
}

This approach is similar to how we can find all the possible prime factors for all the numbers till the given limit

We can also approach this by using the Math library and finding the square root of the number. Then see if the obtained square root is an integer or not.

public class CodingProblemSolution
{
    public static bool IsPerfectSquareBySqRoot(int n)
    {
        double root = Math.Sqrt(n);

        if (root - Math.Floor(root) == 0)
        {
            return true;
        }

        return false;
    }
}
Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.