寻找此函数的循环不变量。

huangapple go评论81阅读模式
英文:

Find loop invariant of this function

问题

我需要找到gcd(欧几里德算法)的循环不变式,但我不知道从何处开始或者要查找什么。

    int f(int x, int y) {
       while (true) {
           int m = x % y;
           if(m == 0) return y;
           x = y;
           y = m;
       }
    }
英文:

I need to find the loop invariant of gcd (euclid algorithm) but i don't know from where to start or what to look

    int f(int x, int y) {
       while (true) {
           int m = x % y;
           if(m == 0) return y;
           x = y;
           y = m;
       }
    }

答案1

得分: 3

最大公约数 x 和 y 在整个循环过程中保持不变。因此,循环不变式是 gcd(x, y) = c,其中 c 是一个常数。

英文:

The greatest common divisor of x and y remains the same throughout the loop. Therefore, a loop invariant is gcd(x,y) = c where c is a constant.

答案2

得分: 2

一个循环不变式是在每次循环迭代中都满足的条件。在你的情况下,你没有基于可以改变的条件进行循环,所以如果循环不变式不是“循环条件始终为真”,那么在每次迭代中唯一成立的另一件事是“变量 m 的值始终显示 x 是否可以被 y 整除”。

英文:

A loop invariant is a condition that is met in every iteration of the loop. In your case, you're not looping on a condition that can change, so if the loop invariant isn't "the loop condition is always true", the only other thing that holds true for every iteration is "the value of m always shows whether x can be divided by y".

huangapple
  • 本文由 发表于 2020年8月31日 04:40:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63661932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定