0

I'm struggling to come up with a loop invariant for the following piece of code:

OddNumber(n)

  1. a = 2
  2. for i = 1 to n do
  3.    a = a * i
    
  4. return a+1

Now, I want to find a loop invariant which is correct before entering the for-loop in l.2. My idea was that a = the product from k=1 to i-1 multiplied with 2, however, I have trouble involving the 1 added in the end.

FishyK
  • 121
  • 1
  • 7
  • `a` is always even - this is the loop invariant. – Eugene Sh. Jul 21 '21 at 18:23
  • then how would I go on to prove this via induction? – FishyK Jul 21 '21 at 18:27
  • Easy. Base is a=2 - it is even. Then an even number multiplied by any other (natural) number is always even too. – Eugene Sh. Jul 21 '21 at 18:29
  • But the value of 1 gets added at the end of the loop, so a can never be even, can it? No matter how often you multiply the value of a by i, in the end you always have to add 1 – FishyK Jul 21 '21 at 18:31
  • So? The invariant is still there, `a` is even. Any even number + 1 is odd. What are you trying to prove? – Eugene Sh. Jul 21 '21 at 18:32
  • Oh okay, I thought the fact that +1 was added needed to be part of the invariant. Since it's not, that makes much more sense now, thank you – FishyK Jul 21 '21 at 18:38

0 Answers0