-2

I only got this far with the answer. I don't understand how recursive functions work. I would really appreciate any help. And also, if someone could explain what base and recursive calls are, that'd be great.

def multi(n):
     if n==1:
         return 4
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

2 Answers2

0

Recursive function is a function that makes a call to it self. for example:

def multi(n):
   if n>0:
        return n * multi(n-1)
   else:
        return 0

To prevent infinit recursion you have to define a case where the function does not make a call to it self.(in our example it's in else statement when n==1).

Kenly
  • 24,317
  • 7
  • 44
  • 60
0

Please try this code :

def multi(n):
    return (5 + multi(n-1)) if n>0 else 0;

this function is a 5n, here's the explanation:

when n = 1 the call is like this :
output : 5 + multi(0) --> multi(0) = 0, so 5 + 0 = 5

It's something like this :

multi(3)
|
-- 5 + multi(2)
|
--- 5 + (5 + multi(1))
|
---- 5 + (5 + (5 + multi(0)))
|
----- 5 + 5 + 5 + 0

5n --> if n = 3 --> 5(3) = 15
output multi(3) = 15, as same as 5(3)=15.

5(3) = 5+5+5 = 15
5(2) = 5+5 = 10

in recursion, you'll do it like this:
5(0) = 0
5(1) = 5 + 0 = 5
5(2) = 5 + 5 + 0 = 10
...
5(n) = 5 + f(n-1), where f(0) = 0, so n must greater than 0. To prevent infinite loop.
Case for 5(3) :
1. 5(3) = 5 + f(2)
2.            f(2) = 5 + f(1)
3.                       f(1) = 5 + f(0)
4.                                  f(0) = 0

So, you will get 5(3) = 5 + (5 + (5 + 0)) = 15

Hope this help you to understand it :D

Eko Junaidi Salam
  • 1,663
  • 1
  • 18
  • 26