Loops 利用循环不变量的算法正确性
我必须用循环不变量证明下面算法的正确性。 它将两个数字表示为数组(逆序:1579->[9 7 5 1]),处理它们的乘法并将结果作为数组返回Loops 利用循环不变量的算法正确性,loops,invariants,Loops,Invariants,我必须用循环不变量证明下面算法的正确性。 它将两个数字表示为数组(逆序:1579->[9 7 5 1]),处理它们的乘法并将结果作为数组返回 ArraysMultiplication(x,y,n) In: x, y — the numbers represented as arrays In: n — the length of arrays Out: p (the array that contains the multiplication result) for i = 0; 2n - 1
ArraysMultiplication(x,y,n)
In: x, y — the numbers represented as arrays
In: n — the length of arrays
Out: p (the array that contains the multiplication result)
for i = 0; 2n - 1 do
p[i] = 0
end for
for i = 0; n - 1 do
remainder = 0
for j = 0; n - 1 do
value = x[j] * y[i] + remainder + p[j + i]
p[j + i] = value mod 10
remainder = value div 10
end for
p[n + i] = remainder
end for
return p
我真的不明白循环不变量对这个算法应该做什么。
提前谢谢 循环不变式将循环的每次迭代简化为一个更简单的谓词,反过来,您可以根据循环不变式对循环进行说明。你试过什么?我试过类似于p(k)=p(k-1)+y*x[k]*10^(k-1),其中p(k)是步骤k之后的结果数组。但我几乎可以肯定这是不正确的,因为我知道我必须对大循环中的循环使用第二个不变量。