12

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;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kaushal
  • 143
  • 1
  • 1
  • 6

1 Answers1

44

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks :) I never knew about this. – Kaushal Oct 12 '12 at 15:47
  • @dasblinkenlight - I just saw that.. did it! – Kaushal Oct 12 '12 at 16:18
  • 3
    @dasblinkenlight - and yes we can easily prove it by drawing squares.. here is a video explaining it https://www.youtube.com/watch?v=2gC5eVRatOQ – Kaushal Oct 12 '12 at 16:24
  • 1
    @user1386320: of course you _can_ learn this at school. School programs are different per country and adapted differently by teachers, so it may be bad luck. – Cœur Oct 11 '18 at 08:20