# Loop Invariants

**URL:** https://forum.codeselfstudy.com/t/loop-invariants/2896
**Category:** Programming Questions
**Created:** [December 13, 2022, 4:42pm UTC](https://forum.codeselfstudy.com/t/loop-invariants/2896 "2022-12-13T16:42:38Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![andy](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/andy/32/3546_2.png) [@andy](https://forum.codeselfstudy.com/u/andy)
#### Post date: [December 13, 2022, 4:42pm UTC](https://forum.codeselfstudy.com/t/loop-invariants/2896/1 "2022-12-13T16:42:38Z")

</div>

I am reading about loop invariants and I don’t understand one thing:

For algorithm

```python
r = c 
while r > 0:
r = 31 * r % 73

```

Is r \< 73 loop invariant?

Answer in the book says yes, but from what I understand loop invariant needs to be true before program enters the loop.  
And we can set `r` to 74 for example so before the loop invariant isn’t true only inside and after the loop it will stay true.

---

<div class="post-metadata">

### Author: ![Dan](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/dan/32/4311_2.png) [@Dan](https://forum.codeselfstudy.com/u/Dan)
#### Post date: [December 13, 2022, 7:47pm UTC](https://forum.codeselfstudy.com/t/loop-invariants/2896/2 "2022-12-13T19:47:25Z")

</div>

I agree with you. Maybe there’s some mention of c before this? Or maybe it’s just an error in the textbook. All textbooks have errors somewhere.

---

<div class="post-metadata">

### Author: ![conradwt](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/conradwt/32/1262_2.png) [@conradwt](https://forum.codeselfstudy.com/u/conradwt)
#### Post date: [December 20, 2022, 7:45pm UTC](https://forum.codeselfstudy.com/t/loop-invariants/2896/3 "2022-12-20T19:45:56Z")

</div>

@andy The loop invariant here is **r \> 0**. Next, the code should be formatted as follows in Python:

```auto
r = c
while r > 0:
  r = 31 * r % 73

```

Note: If c is set to 74, the invariant is true when entering the while loop. For example, **74 \> 0** is true.

---

<div class="post-metadata">

### Author: ![Adrian](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/a/82dd89/32.png) [@Adrian](https://forum.codeselfstudy.com/u/Adrian)
#### Post date: [April 23, 2025, 3:46pm UTC](https://forum.codeselfstudy.com/t/loop-invariants/2896/4 "2025-04-23T15:46:13Z")

</div>

The key point is to consider the initialization of the variable `r`. In the given algorithm, `r` is initially set to `c`, and the invariant `r < 73` holds as long as `c < 73`. If `c` is initially less than 73, then `r < 73` is indeed a loop invariant because it holds before entering the loop, remains true during each iteration, and after the loop terminates. The book assumes `c < 73` for the invariant to be valid throughout. Perhaps that’s the missing context.
