Recursive function simulating a number elevated to a power

Asked

Viewed 4,415 times

7

How to simulate the elevation of a number to a power using the recursion (and Python)?`

1 answer

5


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

to0 = 1

as you probably already know about the math lessons. Where to is the basis.

What is the recursive step after all?

From the math lessons, we know that:

ton + 1 = ton * to

or is our basis to high the power of n + 1 is equal to the same basis to raised to n, times our base to (I just translated it into words).

And how do we solve ton?

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

ton = ton - 1 * to

And so on, applying successively to recursion to:

ton - 1

I think you’ve figured out how to solve.

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 now to apply this function:

print(power_r(4, 3))

using as a basis 4 and as a power 3, the result is:

4^{3} = 4 * 4^{2}
4^{2} = 4 * 4^{1}
4^{1} = 4 * 4^{0}
4^{0} = 1
64

Browser other questions tagged

You are not signed in. Login or sign up in order to post.