0

I have the following recursive function below that returns the k to the s power of a certain integer.

However I do not understand how it works. The base class is 1 when s becomes 0.

How is it so that the returned value is actually k^s when 1 is returned? Since 1 is returned I would expect powertoK(k, s) to be 1 all the time.

Are there 2 memory addresses one holding 1 and the other as k^s?

def powertoK(k, s): 
    if s != 0:
        return k* powertoK(k,s-1)
    else:
        return 1
powertoK(3, 7) 
Luca
  • 344
  • 5
  • 18
Bosser445
  • 303
  • 1
  • 9
  • You have to understand that one (recursive) call adds one level to the call stack and each `return` removes one level. Or in other words: there are as many calls as there are returns (unless there's an exception). And BTW: why is your function called differently than the call? – Klaus D. Apr 08 '23 at 21:30
  • `Traceback (most recent call last): ... return k* power(k,s-1) , NameError: name 'power' is not defined` please fix. – wwii Apr 08 '23 at 21:35
  • Your example boils down to `3 * 3 * 3 * 3 * 3 * 3 * 3 * 1`. Does that help explain things? – John Gordon Apr 08 '23 at 21:35
  • "How is it so that the returned value is actually k^s when 1 is returned?" Well, k to the power 0 is 1, and we only `return 1` when s is equal to 0. In other cases - do you agree that one way to compute k to the power of s, is to compute k to the power of (s-1) and then multiply that result by k? For example, if I want to find the cube of a number, I could find the square of the number first and then multiply it again, right? Then, is that not **exactly what the code says**? – Karl Knechtel Apr 08 '23 at 21:40

1 Answers1

1

This is not related to memory addresses. Look at the different calls that happen during the recursion. I'm using smaller numbers () to keep it shorter:

powertok(2, 3)
= 2 * powertok(2, 2)
= 2 * 2 * powertok(2, 1)
= 2 * 2 * 2 * powertok(2, 0)
= 2 * 2 * 2 * 1
= 8

So only at the end the return value is 1 - but you are multiplying that with all the previous return values, because the initial call to powertok(2, 3) returns 2 multiplied by the return value of powertok(2, 2), and so on, until it gets multiplied by the return value of powertok(2, 0) which is the hardcoded 1 (instead of calling powertok again).

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636