Power x^n Recursively
Compute an integer base raised to a nonnegative exponent recursively. Students follow return values and distinguish the title's mathematical notation from XOR.
1def power(x, n):2 # Base case3 if n == 0:4 return 15 if n == 1:6 return x78 # Recursive case9 return x * power(x, n - 1)1011# Test12x = int(input("Enter base: "))13n = int(input("Enter exponent: "))14result = power(x, n)15print(f"{x}^{n} = {result}")
Output
Enter base: 2 Enter exponent: 5 2^5 = 32
In this one
- Reduce an exponent
- Use multiplicative base cases
- Distinguish notation from XOR
How it works
- 1
Return one at exponent zero or x at one.
- 2
Call power with exponent n - 1.
- 3
Multiply the returned value by x.
Edge cases
What is returned for exponent zero?
What is returned for exponent zero?
One, including the code's chosen 0-to-zero-power convention.
Does this handle negative exponents?
Does this handle negative exponents?
No. Decreasing a negative exponent never reaches the base cases.
What's going on
power(x, n) multiplies x by the result for exponent n - 1. The zero exponent returns one and the one exponent returns x.
The pending multiplications remain on Python's call stack until a base case returns. For base two and exponent three, the result is eight. The ^ in the printed label is only notation; executable ^ would mean XOR, not exponentiation.
What is returned for exponent zero? One, including the code's chosen 0-to-zero-power convention.
Does this handle negative exponents? No. Decreasing a negative exponent never reaches the base cases.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What computes the recursive step?
Pick an answer to check it.
Question 2
What is returned for exponent zero?
Pick an answer to check it.
Questions people ask
What is returned for exponent zero?
One, including the code's chosen 0-to-zero-power convention.
Does this handle negative exponents?
No. Decreasing a negative exponent never reaches the base cases.
What computes the recursive step?
x * power(x, n - 1).
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum