In this article, we will learn about python program to divide two numbers using recursion with examples.
Getting Started
The task is to divide two numbers using recursion. For example,
If a = 9 and b = 3, then output is 9 / 3 = 3. But, we need to do it using recursion.
We can do so in multiple ways –
Simple Approach
- Take static input of two numbers.
- Write function that takes two arguments x and y.
- Inside that function, return 0 if x is less than y. Otherwise, subtract y from x each time function is called.
- In each function call, we are adding 1 to return value.
- Basically, we are keep track of how many times y is subtracted from x so that x becomes less than y.
def divide(x, y): if(x < y): return 0 else: return 1 + divide(x - y, y) x = 658 y = 60 result = divide(x, y) print("Result:", result)
Output:
Result: 10
Result is printed using print() function in python.
Using User Input
- Take input from user using input() function. Then, convert them to integer using int() function.
- Write function that takes two arguments x and y.
- Inside that function, return 0 if x is less than y. Otherwise, subtract y from x each time function is called.
- In each function call, we are adding 1 to return value.
- Basically, we are keep track of how many times y is subtracted from x so that x becomes less than y.
def divide(x, y): if(x < y): return 0 else: return 1 + divide(x - y, y) x = int(input("Enter a number")) y = int(input("Enter another number")) result = divide(x, y) print("Result:", result)
Output:
Enter a number 500 Enter another number 50 Result: 10
Result is printed using print() function in python.
That’s how we can write python program to divide two numbers using recursion with examples.
Reference: Division
Learn about more python examples at – https://tutorialwing.com/python-tutorial/