Generate Uniform 1-7 from Uniform 1-5

Probability · Medium · Free problem
You are given a function `rand5()` that returns a uniformly random integer from 1 to 5. Using only `rand5()`, write a function `rand7()` that returns a uniformly random integer from 1 to 7. **Constraints:** - You may call `rand5()` as many times as needed - Each call to `rand5()` is independent and uniform on $\{1, 2, 3, 4, 5\}$ - Your function must produce each of $\{1, 2, 3, 4, 5, 6, 7\}$ with exactly equal probability $\frac{1}{7}$ **Example 1:** ``` Input: (internal rand5 calls return 2, 3) Output: 8 % 7 + 1 = 2 (since 5*(2-1) + (3-1) = 7, and 7 < 21) ``` **Example 2:** ``` Input: (internal rand5 calls return 5, 5) Output: rejected (since 5*(5-1) + (5-1) = 24 >= 21), retry ```

Open the full interactive solver, hints, and worked solution →