Search code examples
pythonalgorithmrecursiondivisionfloor

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

Solution

  • 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.