0

I apologize if this is a dumb or repeating question firstly. I have been learning python for about 2 weeks now and I keep having small problems with loops. For example.

def factorial(n):

      if n < 2:       # I understand once the number becomes < than 2 the loop continues
        return 1.  #and here we return the value 1
     result = n * factorial(n-1)    #why do we subtract 1 from n?
     return result 
factorial(5) #my random number

I am having trouble understanding why you subtract 1 from n. Shouldn't you add 1 instead to include the number?

In my mind it looks like this: result = n(1) * factorial((1)-1) # doesn't n stay = to 1 or am i mistaken?

Thank you for you help. Sorry again if its an idiot question.

Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41
Roderick
  • 16
  • 3
  • 1
    Think about it: `5! == 5 * 4!`, isn't it. Or generally: `n! == n * (n-1)!`. Following this logic, the recursive calls are made to ever *decreasing* arguments that will eventually reach the base case. – user2390182 Dec 20 '20 at 14:38
  • Oh right, because (n) itself is 0 leading to the number before n. That's why you multiply it with n again. I think I am beginning to understand – Roderick Dec 20 '20 at 15:35
  • This youtube video shows both the iterative and recursive case for implementing factorial: https://youtu.be/wMNrSM5RFMc – axelclk Dec 23 '20 at 16:53

1 Answers1

0

E.g. first you call the function with 5, then would you again call it with 5 and multiply, it will overflow the recursion limit and endless loop.

So, you need to decrement by 1 and then call by 4, 3 and so on and when it is less than 2 return 1.

Wasif
  • 14,755
  • 3
  • 14
  • 34