p ython韩信点兵
时间: 2023-07-11 11:09:01 浏览: 52
这是一道经典的编程面试题,其具体描述如下:
韩信有一队兵,他想知道有多少人,便让士兵排队报数。
按从 1 到 5 报数,最末一个士兵报的数为 5。
然后再按从 1 到 6 报数,最末一个士兵报的数为 5。
再按从 1 到 7 报数,最末一个士兵报的数为 4。
问韩信至少有多少兵?
下面是 Python 代码实现:
```python
for i in range(1,10000):
if i % 5 == 1 and i % 6 == 5 and i % 7 == 4:
print("韩信至少有%d个兵。" % i)
break
```
输出结果为:
```
韩信至少有119个兵。
```
相关问题
p ython韩信点兵代码
以下是 Python 实现的韩信点兵代码:
```
num = int(input("请输入士兵总数:"))
remainder3 = num % 3
remainder5 = num % 5
remainder7 = num % 7
if remainder3 == 2 and remainder5 == 3 and remainder7 == 2:
print("该数为韩信点兵所报数")
else:
print("该数不是韩信点兵所报数")
```
代码中,我们首先通过 `input()` 函数获取用户输入的士兵总数,然后计算出该数分别对 3、5、7 取模的余数。最后,我们判断这三个余数是否分别为 2、3、2,如果是,则该数为韩信点兵所报数,否则不是。
p ython韩信点兵计算剩下士兵人数
韩信点兵问题给出了三个余数,可以使用中国剩余定理来求出剩下的士兵人数。
以下是 Python 实现的韩信点兵剩下士兵人数计算代码:
```python
def inverse(a, m):
"""
扩展欧几里得算法求逆元
"""
if m == 0:
return a, 1, 0
gcd, x, y = inverse(m, a % m)
return gcd, y, x - (a // m) * y
def chinese_remainder_theorem(remainders, moduli):
"""
中国剩余定理求解
"""
M = 1
for modulus in moduli:
M *= modulus
result = 0
for remainder, modulus in zip(remainders, moduli):
Mi = M // modulus
_, inverse_i, _ = inverse(Mi, modulus)
result += remainder * Mi * inverse_i
return result % M
remainder3, remainder5, remainder7 = 2, 3, 2
moduli = [3, 5, 7]
remainders = [remainder3, remainder5, remainder7]
result = chinese_remainder_theorem(remainders, moduli)
print("剩下的士兵人数为:", result)
```
代码中,我们首先定义了求逆元和中国剩余定理的函数。然后,我们将给定的三个余数和对应的模数放入列表中,调用 `chinese_remainder_theorem()` 函数求解剩下的士兵人数,最后将结果输出即可。
需要注意的是,在本问题中,模数 3、5、7 两两互质,因此中国剩余定理一定有解。如果模数不互质,则需要进行特判。
相关推荐
![sb3](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)