Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 什么';这段代码的循环不变量是什么?_Loops_While Loop_Proof_Loop Invariant - Fatal编程技术网

Loops 什么';这段代码的循环不变量是什么?

Loops 什么';这段代码的循环不变量是什么?,loops,while-loop,proof,loop-invariant,Loops,While Loop,Proof,Loop Invariant,我需要为给定的代码片段找到一个循环不变量: //pre: x & y >= 0 //post: z = x^y //computes pow(x, y), x^y int pow(int x, int y){ int z = 1; while(y > 0){ if(y%2==0){ y /= 2; x = x*x; }else{ z = z*x;

我需要为给定的代码片段找到一个循环不变量:

//pre: x & y >= 0
//post: z = x^y
//computes pow(x, y), x^y
int pow(int x, int y){
    int z = 1;
    while(y > 0){
        if(y%2==0){
            y /= 2;
            x = x*x;
        }else{
            z = z*x;
            y -= 1;
        }
    }
    return z;
}
我的不变量是:

{(ypre - 0 = 0 & x = x^(ypre  -y)) OR (ypre - y != 0 & x^(n + m) = x^(ypre - y), where (n=ypre-y) and (m=integer value of z/x))}

这是一个混乱的不变量,我不能100%确定它是正确的。是否有更好的不变量可以覆盖z=x^y的后置条件?我建议使用一个循环变量

  • x'^y'==(x^y)/z
    (其中
    x'
    y'
    是任何迭代后修改的输入)

  • x'>=x
    0希望这是在中发布此内容的正确站点。x^y是。。。x或y?(我没那么傻,但说出你的意思肯定会很有帮助)当x=2,y=3时呢?在第三次迭代中,x=4,y=1,所以4^1!=2^1.@Brandon oops我省略了等式的系数
    z
    。修正了。你能告诉我你是如何得出这个结论的吗?这个解决方案是如此干净和简单。看看这两个分支。问你自己(a)为什么它一定会结束(b)为什么答案仍然正确?