views:

204

answers:

1

Hi,

I've been given the following problem about loop invariants:

Consider

x=4; for(i=5;i<k;i++) { a=a+x+i; x=x*2; }

Define the appropiate loop invariant that utilizes a closed formula for a and x.

Now, How do you know you have the right loop invariant here? I mean you can set the loop invariant to be: "At j'th iteration 'x' is less than 'a'" which will be correct but will not use any closed formulas right?

How can a statement (the loop invariant) can be used to determine the value of "a" when the loop is over? All the examples I've seen just state the loop invariant and its not being used as a closed formula.

Any ideas?

Thanks for all of your help.

+2  A: 

Start with the closed formulas: clearly for x(j) [for j from 0 to k-5], x at entry to the j-th leg of the loop, x(j+1) = x(j) * 2, so, x(j) is 4 * 2**j (using ** for "raise to power") since x(0) is 4; and a(j+1) = a(j) + x(j) + j + 5 -- we're not told what a(0) is, but we can factor it out and write a(j) as a(0) + something. Can you figure out what that something is, given the above closed-formula resoution for x(j)? I'm reluctant to do your homework from you -- have you yet started studying Concrete Mathematics or whatever your textbook IS...?

Once you're written down the closed-form formula for a(j), to go with the trivial one I supplied for x(j), can you see how they combine to make a loop invariant...?

Alex Martelli
Hi,I actually had that same recursive relation set up for this already but did not know if I was on the right track.Well, from a(j+1) we know that a(0)=0 giving us for a(0)=0+4+0+5=9.Is the closed-form formula expressed in terms of j with no recursive relations in it? Not even using x(j)?the expression that i have is:a(j)=a(j-1)+x(j-1)+(j-1)+5
pcp
Correction:a(1)=0+4+0+5=0
pcp
@pcp, so you have the recurrence relation: a(k) is the sum over k of 5 - 1 (that is 4 times j, of course) plus the sum over k of k (which is half of j times j + 1) plus the sum over k of 4 times `2**k` (which is 4 times `2**j` minus one). So, can you express a(k) as a function strictly of k? That's "closed form". Easy to make off-by-1s, but also easy to check the formula vs a little iterative computation. So then the invariant will essentially be a statement of the value of a as a function of i.
Alex Martelli