gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Loop invarient example
- User
Loop invarient example
- Assistant
A common example of a loop invariant is the process of calculating the factorial of a number.
Consider the following code snippet that calculates the factorial of a given number
n:pythondef factorial(n): result = 1 for i in range(1, n+1): result = result * i return resultIn this case, a loop invariant could be that
resultalways holds the factorial of the numbers encountered so far.Formally, we can define the loop invariant as follows:
result = 1before entering the loop, which represents the factorial of 0 (0!). This holds true outside the loop.- For each iteration of the loop,
resultis multiplied byi, which is a number from 1 ton. Therefore, after each iteration,resultholds the factorial of the numbers encountered so far, up to numberi. This also holds true inside the loop. - After the loop finishes, will hold the factorial of since it has been multiplied by all the numbers from 1 to . This also holds true after the loop.