How to find the loop invariant

I know that the loop invariant is intended to prove the correctness of the problem, but I cannot figure out how to do this, whatever the trivial problem. Here is an example. Can someone indicate which step I should consider in order to come up with one. I know that all values ​​that change in a loop should be related to my invariant. Please help me with this problem, I also have to find the post state. An explanation will cost more than an answer; please, help.

{M > 0 and N >= 0 }

a = M;
b = N;
k = 1;

while (b > 0) {
    if (b % 2 == 0) {
        a = a * a;
        b = b / 2
    } else {
        b = b – 1;
        k = k * a;
    }
}

{ ? ? }
+4
source share
2 answers

The tricky part about loop invariants is that there is no algorithm (which I know) that will always guarantee a “correct” answer.

, , (: - ). a, b k.

, M = 2 N = 1,2,3,.... N , a, b k .

, - , .

, !

+1

, . , - . , , , , , , , .

... ? ? .

: k =... b..... b == 0, ...., .

, , , , , .

0

Source: https://habr.com/ru/post/1612294/


All Articles