The loop invariant

1
2
3
4
5
p=1
i=0
while p<n:
    p=2*p
    i+=1

Consider the above fragment of code, with n n , p p and i i as integer variables. What is the loop invariant of the code?

Definition : A loop invariant is a condition that is necessarily true immediately before and immediately after each iteration of a loop

p = ( i + 1 ) 2 p=(i+1)^{2} p = 2 i p=2^{i} p = 2 i + 1 p=2^{i+1} p = ( i + 1 ) 2 i p=(i+1)2^{i} p = i + 1 p=i+1

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

  • [ Initiation ] Before the loop, i = 0 i = 0 and p = 1 p = 1 . Hence, p = 2 i p = 2^i
  • [ Iteration ] Assume that before an iteration, we have i = i i = i' and p = 2 i p = 2^{i'} . Line 4 changes p 2 p = 2 2 i = 2 i + 1 p \leftarrow 2 p = 2 \cdot 2^{i'} = 2^{i' + 1} and line 5 changes i i + 1 i \leftarrow i'+1

Hence, by induction, after any iteration p = 2 i p = 2^i holds.

Sam Bealing
Jun 28, 2016

The situation after k l o o p s k \: loops is that p = 2 k p=2^k and i = k i=k it therefore follows the loop invarient is p = 2 i \boxed{\boxed{p=2^i}}

Moderator note:

Not quite. You have to explain why the step of the loop doesn't change the fact that p = 2 i p = 2^i .

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...