Search code examples
pythonloopssum

Recursively subtracting a second value from a first while keeping count then return the count


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 div ():
    n=0
    m=0
    count=0
    n=input("Enter first Integer:")
    m=input("Enter second Integer:")
if n<m:
    return 0
else:
n= int(n)-int(m)
count=count+1
    print (count)
    n+=1

Solution

  • First you could get all values and convert to int() and later you could run recursive function with these values as arguments

    def subtrack(n, m):
        if n < m:
           return 0
    
        count = subtrack(n-m, m) + 1
        
        return count
    
    # --- main ---
    
    n = int(input("Enter first Integer:"))
    m = int(input("Enter second Integer:"))
    
    count = subtrack(n, m) 
    
    print(count)
    ``