Recursive function that simulates a number raised to a power

6

How to simulate raising a number to a power using recursion (and Python)? '

    
asked by anonymous 06.01.2015 / 17:54

1 answer

4

Knowing that I have to use recursion , the first thing to find is the base case. In this case, the base case is:

a 0 = 1

As you probably already know from math lessons. Where a is the basis.

What, after all, is the recursive step?

From the math lessons, we know that:

a n + 1 = a n * a

ie our base a high power of n + 1 is equal to the same base a to n , sometimes our base a (only translated into words).

And how do we resolve n ?

Exactly, here comes the crux, where we apply the definition of recursion :

a n = a n - 1 * a

And so on, by successively applying recursion to:

a n-1

I think I've already figured out how to solve it.

Translating in Python (in this case):

def power_r(base, power, show_steps=True):
    """show_steps serve só para dizer 
    se amostrar os passos recursivos escritos ou não."""
    if power == 0: # caso base
        if show_steps:
            print(base, "^{0} = 1", sep="")        
        return 1
    else: # passo recursivo
        if show_steps:
            print(base, "^{", power, "} = ", base, " * ", base, "^{", power - 1, "}", sep="")
        return base * power_r(base, power - 1, show_steps)

Trying to apply this function now:

print(power_r(4, 3))

using 4 and as power 3 , the result is:

4^{3} = 4 * 4^{2}
4^{2} = 4 * 4^{1}
4^{1} = 4 * 4^{0}
4^{0} = 1
64
    
06.01.2015 / 17:55