简体   繁体   中英

recursive function for floor division

I am creating a recursive function that essentially operates floor division without using the ' // ' operator. I have figured out the function, but only when input n is positive and I am struggling to figure out how to operate the function when n < d. Any help is greatly appreciated, thanks!

My current code:

def quotient( n , d ):

    if (n >= d):
        return quotient(n - d, d) + 1

    else: 
        return n

You can do it like that:

def quotient( n , d ):

    if (0<=n<d):
        return 0
    if (n >= d):
        return quotient(n - d, d) + 1
    if n<0:
        return quotient(n + d, d) - 1

If 0<=n<d the quotient is 0, this is the first if . If n is negative, we handle it in a similar fashion to the positive case, just switch the signs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM