Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

algorithm - 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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...