1

I am having some issues finding the invariant for the algorithm below.Also,I have to follow all the steps to proof how i find the specific invariant and I don't know how I can demonstrate that. I saw that this algorithm is a multiplication by adding.

The algorithm is:

alg1(integer a,b)
 x<-a
 y<-b
 z<-0
 while y>0 do
   z<-z+x
   y<-y-1
 end while
 return z

I hope someone can help share some light on this for me, as the similar cases I've found in here, have not been sufficient.

Thanks alot in advance for your time.

2 Answers2

0

Hint:

The body of the loop shows that z grows from zero by increments x, while y decreases to zero by units. Hence, z + x y is probably constant...

0

Loop invariant: At the start of kth iteration, value of z is k-1 multiplied by x.

Proving correctness:
Initialization
At beginning, k=1, so

z= (1-1) * x
z= 0 *z=0

Maintenance
If at start of kth iteration, z =(k-1)x where k-1< n then within loop z gets multiplied by z and the end of iteration z =kx. This shows loop invariant holds true for k+1 th iteration.

Termination:
At termination,

k=y+1: 
z=(y+1)-1 * x
z=yx

z becomes product of y and x

amol goel
  • 149
  • 3