22.5k views
1 vote
Write a recursive method named factorial that accepts an integer n as a parameter and returns the factorial of n, or n!. A factorial of an integer is defined as the product of all integers from 1 through that integer inclusive. For example, the call of factorial(4) should return 1 * 2 * 3 * 4, or 24. The factorial of 0 and 1 are defined to be 1. You may assume that the value passed is non-negative and that its factorial can fit in the range of type int. Do not use loops or auxiliary data structures; solve the problem recursively.

1 Answer

4 votes

Answer:

The function in Python is as follows:

def factorial(n):

if n == 1 or n == 0:

return n

else:

return n*factorial(n-1)

Step-by-step explanation:

This defines the function

def factorial(n):

This represents the base case (0 or 1)

if n == 1 or n == 0:

It returns 0 or 1, depending on the value of n

return n

If n is positive, then this passes n - 1 to the factorial function. The process is repeated until n = 1

else:

return n*factorial(n-1)

User Mlzboy
by
5.7k points