Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 3 - Level 1: Basic RecursionExample 7 of 10
power-x-n-recursively.py
1def power(x, n):
2 # Base case
3 if n == 0:
4 return 1
5 if n == 1:
6 return x
7
8 # Recursive case
9 return x * power(x, n - 1)
10
11# Test
12x = 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. 1

    Return one at exponent zero or x at one.

  2. 2

    Call power with exponent n - 1.

  3. 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).