Question

To prove the correctness of the following:

# pre: int >= 1

fac = 1
i = n
while i>0:
     fac = fac*i
     i = i-1

# post: fac = n!

which loop invariant do we need?

(Hint, you will need two statements that are both true. One about fac and one about i)

2. To prove correctness of the following: # pre: int n>=1 fac 1 while i>0: fac = fac치 i = i-1 # post: fac n! which loop invar

Please provide both full statements as well as which loop invariant is needed in a full proof.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

# pre: int >= 1

fac = 1
i = n
while i>0:
fac = fac*i
i = i-1

# post: fac = n!

statement 1:loop invariant would be fac*(i!) = n! where n is the initial value of i that is passed to the function. This statement is always true, no matter how many iterations of the loop have already been done.

statement 2: in each iteration value of i reduced by 1 till it reaches 0
proof:
Precondition :
i = n ,fac=1
fac*(i!) = 1*(n!) = n!

Maintenance :
in each iteration fac = fac*i
and i=i-1;
(fac*i)*((i-1)!) = n!

Termination :
fac = 1*2*3*4*.........*(n-1)*n = n!

Add a comment
Know the answer?
Add Answer to:
To prove the correctness of the following: # pre: int >= 1 fac = 1 i...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT