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;
}
}
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 squarek+1
from squarek
requires adding2k+1
unit squares.