문제

How would I get a loop invariant and prove it for the following algorithm.

power(x,y):
   z = 1
   m = 0
   while m < y:
       z = z*x
       m = m+1
   return z
도움이 되었습니까?

해결책

Firstly, I think you mean z = z*x To show the loop invariant for any given loop, you have to come up with a statement that doesn't change at the beginning and end of any iteration. Using that invariant, you will prove that when the program terminates, the function works. your function power is basically trying to do x^y.

Lets construct a loop invariant: Z = x^m. You can see that this is true both at the beginning and end of the loop.

You also know that loop can only exit when not(m= y, or m =y.

So if Z=x^m, and upon termination m = y. Then Z = x^y.

So we can see that this program is partially correct.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top