Home > Mobile >  Calculating Div and Mod using recursion
Calculating Div and Mod using recursion

Time:02-19

I am fairly new to Python trying my best to wrap my head around this however it's a lot harder than I thought. I am attempting to write recursive functions in python that calculate div and mod. div takes two integers as input and keeps on subtracting the second from the first until the first number becomes less than the second number. The function keeps a track of how many times the second number is subtracted from the first and returns that number as the answer. mod also takes two integers as input and keeps on subtracting the second from the first until the first number becomes less than the second number. When the first number becomes less than the second, the value of the first number is the answer.

def lastDigit(x):
 return mod(x,10)



def allButLast(x):
 return div(x,10)

Any help would be great thank you.

CodePudding user response:

The following works as long as p>=0 and q>0.

def mod(p,q):
    if p<q:
        return p
    return mod(p-q,q)

def div(p,q):
    if p<q:
        return 0
    return 1 div(p-q,q)
  • Related