How does the recursion works here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How does the recursion works here?

I've watched videos about the hanoi's tower and i understand the P(n)=2^n-1 but how this apply to this: function power (base, exponent) { if (exponent == 0) return 1; else return base * power(base, exponent - 1); } it's from eloquent javascript and i'm really stucked on this p.s.: Explain like i'm 5, thanks in advance for your help c:

12th Aug 2017, 2:33 AM
Ilean
Ilean - avatar
2 Answers
+ 9
Try to expand it on paper whenever you get stuck. e.g. power(2, 4) 2 * power(2, 3) 2 * 2 * power(2, 2) 2 * 2 * 2 * power(2, 1) 2 * 2 * 2 * 2 * power(2, 0) // exp is now 0 2 * 2 * 2 * 2 * 1 16
12th Aug 2017, 2:50 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
Thank you so much yes i tried this but at the moment of doing it that -1 was a bit tricky for me sorry haha
12th Aug 2017, 3:09 AM
Ilean
Ilean - avatar