Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Determine Whether a Given Number is Even or Odd Recursively
When determining whether a number is even or odd, we typically use the modulo operator. However, we can also solve this problem recursively by repeatedly subtracting 2 until we reach a base case.
Recursion breaks down the problem into smaller subproblems. Here, we reduce the number by 2 in each recursive call until we reach 0 (even) or 1 (odd).
How the Recursive Approach Works
The algorithm works by:
- Base case: If the number is less than 2 (0 or 1), check if it's divisible by 2
- Recursive case: Subtract 2 from the number and call the function again
Example
Below is a demonstration of the recursive approach ?
def check_odd_even(my_num):
if (my_num < 2):
return (my_num % 2 == 0)
return (check_odd_even(my_num - 2))
# Test with different numbers
test_numbers = [48, 35, 0, 1, 7, 12]
for number in test_numbers:
if check_odd_even(number):
print(f"{number} is even")
else:
print(f"{number} is odd")
48 is even 35 is odd 0 is even 1 is odd 7 is odd 12 is even
Step-by-Step Execution
Let's trace how the function works with number 5:
check_odd_even(5)
? check_odd_even(3) # 5 - 2 = 3
? check_odd_even(1) # 3 - 2 = 1
? 1 % 2 == 0 # Base case: False (1 is odd)
? False
? False
? False (5 is odd)
Alternative Implementation
Here's another recursive approach using positive and negative checks ?
def is_even_recursive(n):
# Handle negative numbers
if n < 0:
n = -n
# Base cases
if n == 0:
return True
elif n == 1:
return False
else:
return is_even_recursive(n - 2)
# Test the function
numbers = [8, 15, -6, -3, 0]
for num in numbers:
result = "even" if is_even_recursive(num) else "odd"
print(f"{num} is {result}")
8 is even 15 is odd -6 is even -3 is odd 0 is even
Explanation
- The function
check_odd_eventakes a number as parameter - If the number is less than 2, it checks the remainder when divided by 2
- For numbers ? 2, the function calls itself with the number decremented by 2
- This continues until we reach the base case (0 or 1)
- The final result determines if the original number is even or odd
Conclusion
Recursive even/odd checking works by repeatedly subtracting 2 until reaching a base case. While less efficient than the modulo operator, it demonstrates how recursion can solve mathematical problems by breaking them into smaller subproblems.
