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;
}
}
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.
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…
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.
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.
Because all perfect squares are sums of consecutive odd numbers:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With