首页 > 解决方案 > 返回余数的递归函数

问题描述

我被指示在 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))

标签: pythonfunctionrecursion

解决方案


关于什么

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

矮得多 ...


推荐阅读