loops - 了解循环不变式。寻找并证明它们的算法

标签 loops

我需要一些帮助来理解循环不变式。我只需要有人解释如何找到循环不变式并为以下算法证明它:

public int sumSquares ( int n )
{
    int sum = 0 ;
    for ( int i = 1 ; i <= n ; i++)
    {
        sum += i ∗ i ;
    }
    return sum ;
}

最佳答案

循环不变量是在循环的每次迭代之前和之后都可证明为真的语句。事实证明有很多这样的方法,但关键是证明其中一个确实有帮助。

例如,确实如此

the value of i is always equal to i before and after each iteration.

不是很有帮助。相反,想想你想证明什么

When i is equal to n, sum is equal to the sum of the first n squares

在这种情况下,如果您想证明您的算法产生前 n 个平方的和,您需要声明以下不变量。对于每个i

The value of sum is equal to the sum of the first i squares

关于loops - 了解循环不变式。寻找并证明它们的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32595584/

相关文章:

python - 迭代列表并将输出存储在新列表中的更好方法

jquery - 如何使用 Ajax onclick 加载 WordPress Post

arrays - 使用循环查找特定数组

python - 猜谜游戏中输入多个相同的数字;循环停止工作?

java - 如何在 Java 中实现 Ruby 的 ".each"方法?

php - 使用循环创建 MySQL 查询

PHP 函数循环检查数据库中是否存在字符串

javascript - 如何循环遍历js对象中的项目?

java - 循环遍历每个方向依次递增的 3d 矩阵?

javascript - 循环访问通过 URL 链接的 API 结果页面