16.7k views
0 votes
Write a recursive algorithm to compute a^b, where a and b are nonnegative integers.

User Tamara
by
7.8k points

1 Answer

1 vote

Final answer:

To compute a^b, use a recursive algorithm: if b is equal to 0, return 1; otherwise, recursively call the algorithm with b-1 and multiply the result with a.

Step-by-step explanation:

To compute a^b, we can use a recursive algorithm. Here's one way to do it:

Base case: If b is equal to 0, return 1.

Recursive case: If b is greater than 0, recursively call the algorithm with b-1 and multiply the result with a.

Here's the algorithm in pseudocode:

function power(a, b):
if b == 0:
return 1
else:
return a * power(a, b-1)

For example, if we want to compute 2^3, the algorithm would go through the following steps:
power(2, 3) = 2 * power(2, 2) = 2 * 2 * power(2, 1) = 2 * 2 * 2 * power(2, 0) = 2 * 2 * 2 * 1 = 8

User Mortennobel
by
6.9k points