Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perfect square or not?

This is a code to check if a number is perfect square or not. Why does it work ?

static bool IsSquare(int n)
{
    int i = 1;
    for (; ; )
    {
        if (n < 0)
            return false;
        if (n == 0)
            return true;
        n -= i;
        i += 2;
    }
}
like image 479
Kaushal Avatar asked Oct 12 '12 15:10

Kaushal


People also ask

How do you know if it is a perfect square or not?

To check the perfectness of your square, you can simply calculate the square root of a given number. If the square root is an integer, your number is the perfect square. Let's calculate the squares of the following numbers: 49 and 53 . √49 = 7 - 7 is an integer → number 49 is a perfect square.

Which is not a perfect square?

The square of a number is that number times itself. Here are the square roots of all the perfect squares from 1 to 100. A non-perfect square is every number that is not the result of squaring an integer with itself. 2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26 etc…

Is a perfect square Yes or no?

Informally: When you multiply an integer (a “whole” number, positive, negative or zero) times itself, the resulting product is called a square number, or a perfect square or simply “a square.” So, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, and so on, are all square numbers.

Is 4 a perfect square or not?

The first 12 perfect squares are: {1, 4, 9, 25, 36, 49, 64, 81, 100, 121, 144...} Perfect squares are used often in math. Try to memorize these familiar numbers so that you can recognize them as they are used in many math problems. The first five squares of the negative integers are shown below.


1 Answers

Because all perfect squares are sums of consecutive odd numbers:

  • 1 = 1
  • 4 = 1 + 3
  • 9 = 1 + 3 + 5
  • 16 = 1 + 3 + 5 + 7

and so on. Your program attempts to subtract consecutive odd numbers from n, and see if it drops to zero or goes negative.

You can make an informal proof of this by drawing squares with sides of {1,2,3,4,...} and observe that constructing a square k+1 from square k requires adding 2k+1 unit squares.

like image 94
Sergey Kalinichenko Avatar answered Oct 16 '22 10:10

Sergey Kalinichenko