Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive factorial function

How can I combine these two functions into one recursive function to have this result:

factorial(6)

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

This is the current code for my factorial function:

def factorial(n):
   if n < 1:   # base case
       return 1
   else:
       return n * factorial(n - 1)  # recursive call


def fact(n):
   for i in range(1, n+1 ):
       print "%2d! = %d" % (i, factorial(i))

and the output that this code produces is the following:

fact(6)

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

As you see, the execution of these two functions gives me correct answers, but I just wanted to simplify the two functions to a single recursive function.

like image 391
user531225 Avatar asked Dec 21 '10 18:12

user531225


People also ask

What type of recursion is factorial?

Linear Recursive The factorial function is a good example of linear recursion.


1 Answers

We can combine the two functions to this single recursive function:

def factorial(n):
   if n < 1:   # base case
       return 1
   else:
       returnNumber = n * factorial(n - 1)  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber
like image 164
pythonFoo Avatar answered Oct 18 '22 14:10

pythonFoo