Here's a recursive function to calculate a raised to the power of b, where b is a non-negative integer.
Core Idea of Recursion for Power:
Base Case: Any number raised to the power of 0 is 1 (e.g., 5^0 = 1, 100^0 = 1). This is our stopping condition.
Recursive Step:a^b can be defined as a * a^(b-1). We break down the problem into a smaller, similar problem until we reach the base case.
python
def power(a, b):
"""
Calculates 'a' raised to the power of 'b' using recursion.
Args:
a (int or float): The base number.
b (int): The non-negative exponent.
Returns:
int or float: The result of a^b.
Raises:
ValueError: If b is a negative integer.
"""
if not isinstance(b, int) or b < 0:
raise ValueError("Exponent 'b' must be a non-negative integer.")
# Base case: any number raised to the power of 0 is 1
if b == 0:
return 1
# Recursive step: a^b = a * a^(b-1)
else:
return a * power(a, b - 1)
# --- Test Cases ---
print(f"2^3 = {power(2, 3)}") # Expected: 8
print(f"5^2 = {power(5, 2)}") # Expected: 25
print(f"10^0 = {power(10, 0)}") # Expected: 1
print(f"7^1 = {power(7, 1)}") # Expected: 7
print(f"0^5 = {power(0, 5)}") # Expected: 0
print(f"0^0 = {power(0, 0)}") # Expected: 1 (common mathematical convention in programming contexts)
print(f"1.5^2 = {power(1.5, 2)}") # Expected: 2.25
try:
print(f"2^-1 = {power(2, -1)}")
except ValueError as e:
print(f"Error: {e}")
try:
print(f"2^1.5 = {power(2, 1.5)}")
except ValueError as e:
print(f"Error: {e}")
Explanation:
Input Validation: The first lines if not isinstance(b, int) or b < 0: ensure that b is indeed a non-negative integer, as specified. If not, it raises a ValueError.
Base Case (if b == 0:): When the exponent b becomes 0, the recursion stops. According to the rules of exponents, any non-zero number raised to the power of 0 is 1. (For 0^0, it's often considered 1 in programming contexts, which this function also returns).
Recursive Step (else: return a * power(a, b - 1)):
If b is not 0, the function calls itself (power(a, b - 1)) with b decremented by 1.
This result is then multiplied by a.
This process continues until b eventually reaches 0, triggering the base case and unwinding the recursion, performing all the multiplications along the way.
How power(2, 3) works step-by-step:
power(2, 3)
b is not 0.
Returns 2 * power(2, 2)
power(2, 2)
b is not 0.
Returns 2 * power(2, 1)
power(2, 1)
b is not 0.
Returns 2 * power(2, 0)
power(2, 0)
b is 0.
Returns 1
Now the calls unwind:
power(2, 1) receives 1 from power(2, 0), so it calculates 2 * 1 = 2.
power(2, 2) receives 2 from power(2, 1), so it calculates 2 * 2 = 4.
power(2, 3) receives 4 from power(2, 2), so it calculates 2 * 4 = 8.