# Random Number 1 to 7 With Equal Probability

Given a function rand5() which generated random numbers from 0 to 5. Use this function to create rand7(). In deep approach was asked and further discussion was made regarding how to generalize it for creating `m` random number generator from `n` random number generator. Plz give solution with proper explanation.

## Analysis

> 链接：<https://www.nowcoder.com/questionTerminal/a475db9aa74747709e65399c0c7d86d2>
>
> 来源：牛客网
>
> 可推广至更加一般的情况，对于利用可以产生1\~N的随机数ranN()，生成1\~M的随机数，只需要满足
>
> MAX((randN()-1) \* N + (randN()-1)) >= M都可以使用以上述方法类似的方法实现。
>
> 令 n = N-1 (randN()-1) \* N + (randN()-1) 将以等概率生成N进制数 0 \~nn （换成十进制为 (N-1)\*10 + (N-1)）。 为了让新生成的随机数等概率， 只取前0 \~ (M\*k-1） 个数（M\*k-1\<nn均可） 余M + 1
>
> 求得 randM()随机数

### Reference:

* \[将生成1-5随机数函数转换为1-7随机数函数的实现方法] ([https://www.jianshu.com/p/71d816fae2e4\\](https://www.jianshu.com/p/71d816fae2e4\)/)&#x20;
* \[已知rand7()可以产生1\~7的7个数(均匀概率),利用rand7() 产 生 rand10() 1\~10(均匀概率)。]\([https://www.nowcoder.com/questionTerminal/9d06d8f45dca4e45be41d29c389d8a8d\\](https://www.nowcoder.com/questionTerminal/9d06d8f45dca4e45be41d29c389d8a8d\)/)
* \[给定能随机生成整数 1 到 5 的函数,写出能随机生成整数 1 到 7 的函数。]\([https://www.nowcoder.com/questionTerminal/a475db9aa74747709e65399c0c7d86d2\\](https://www.nowcoder.com/questionTerminal/a475db9aa74747709e65399c0c7d86d2\)/)
* \[CSDN: 随机数生成器 ]\([https://blog.csdn.net/yiqiangeliyou/article/details/46823595\\](https://blog.csdn.net/yiqiangeliyou/article/details/46823595\)/)
* \[GeeksforGeeks]\([https://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/\\](https://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/\)/)

## Solution

```python
# Author：流月0
# Link：https://www.jianshu.com/p/71d816fae2e4

import random


# 原有生成１－５随机数的函数
def random_5():
    return random.randint(1, 5)


# 要获得的生成１～７随机数的函数
def random_7():
    while True:  # 避免没有返回值
        n = (random_5()-1)*5 + random_5()-1  # 生成0～24的随机数
        if n <= 20:
            return n % 7 + 1


if __name__ == '__main__':
    print(random_7())
```
