python - 返回余数的递归函数
问题描述
我被指示在 Python 中定义一个递归函数,该函数找到 n 除以 b 的余数,条件是不使用 "/" 、"%" 或 "//" 运算符。我已经定义了以下函数,它适用于正数。有没有更好的方法使用递归和简单条件来做到这一点。
def division(n, b, q = 1):
"""
parameters : a et b (integers)
returns: the remainder of a and b
pre-requisites : q = 1
"""
if n <= 0 or n < b:
if n == 0:
print("Your division has no remainder.")
elif n in range(0,5):
print("Your remainder is", n)
return 0
else:
return division(n - b, b, q) + q
print(division(274,5))
解决方案
关于什么
def remainder(n, q):
if(n < q):
return n
return remainder(n - q, q)
print(remainder(274, 5)) # will return: 4
print(remainder(275, 5)) # will return: 0
print(remainder(123, 3)) # will return: 0
矮得多 ...
推荐阅读
- java - 为什么kitkat的锁屏按钮被按了两次
- javascript - 与 Threejs 中的 Click 事件相比,鼠标悬停无法正常工作
- python - 如果我通过 slow.next 而不是 mid 为什么合并排序不起作用?
- javascript - JavaScript查找/比较和更新度量/多维数组的重复元素
- python - 传递给 opencl 内核的数组不正确
- reactjs - 反应本机 web 视图 azure aad 身份验证
- python - 如何在 Google Cloud Composer 工作节点上更新 gcloud?
- python - Django没有在模板中呈现python变量
- visual-studio - How to add Auto Brackets in Visual studio Code like in JetBrains IDE?
- c - 如何用const代替#define实现#include判断?