完美的正方形与否? [英] 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;
}
}
推荐答案
因为所有理想平方都是连续奇数的和:
Because all perfect squares are sums of consecutive odd numbers:
- 1 = 1
- 4 = 1 + 3
- 9 = 1 + 3 + 5
- 16 = 1 + 3 + 5 + 7
- 1 = 1
- 4 = 1 + 3
- 9 = 1 + 3 + 5
- 16 = 1 + 3 + 5 + 7
,依此类推。您的程序尝试从 n
中减去连续的奇数,然后看它是否降为零或变为负数。
and so on. Your program attempts to subtract consecutive odd numbers from n
, and see if it drops to zero or goes negative.
您可以通过绘制边为 {1,2,3,4,...}
的正方形并观察构造一个<$ c $正方形 k
中的c> k + 1 需要添加 2k + 1
单位正方形。
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.
这篇关于完美的正方形与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文