Hướng dẫn def factorial(n python)

View Discussion

Nội dung chính

  • 1.Recursive approach: 
  • 2. Iterative approach :
  • 3. One line Solution (Using Ternary operator): 
  • 4. By using In-built function : 
  • Method: Using numpy.prod 
  • Output 

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.

    Hướng dẫn def factorial(n python)

    1.Recursive approach: 

    python3

    def factorial(n):

        return 1 if (n==1 or n==0) else n * factorial(n - 1);

    num = 5;

    print("Factorial of",num,"is",

    factorial(num))

    Output:

    Factorial of 5 is 120

    Time Complexity: O(n)
    Auxiliary Space: O(n)

    2. Iterative approach :

    Method1:

    python3

    def factorial(n):

        if n < 0:

            return 0

        elif n == 0 or n == 1:

            return 1

        else:

            fact = 1

            while(n > 1):

                fact *= n

                n -= 1

            return fact

    num = 5;

    print("Factorial of",num,"is",

    factorial(num))

    Output:

    Factorial of 5 is 120

    Time Complexity: O(n)
    Auxiliary Space: O(1)

    Method2: 

    Python3

    def factorial(n):

        res = 1

        for i in range(2, n+1):

            res *= i

        return res

    num = 5;

    print("Factorial of", num, "is",

    factorial(num))

    Output

    Factorial of 5 is 120

    Time Complexity: O(n)
    Auxiliary Space: O(1)

    3. One line Solution (Using Ternary operator): 

    Python3

    def factorial(n):

        return 1 if (n==1 or n==0) else n * factorial(n - 1)

    num = 5

    print ("Factorial of",num,"is",

          factorial(num))

    Output:

    Factorial of 5 is 120

    Time Complexity: O(n)
    Auxiliary Space: O(n)

    Please refer complete article on Program for factorial of a number for more details!

    4. By using In-built function : 

    In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.factorial() function returns the factorial of desired number.

    Syntax: math.factorial(x)

    Parameter:
    x: This is a numeric expression.

    Returns:  factorial of desired number.

    Python3

    import math

    def factorial(n):

        return(math.factorial(n))

    num = 5

    print("Factorial of", num, "is",

          factorial(num))

    Output:

    Factorial of 5 is 120

    Method: Using numpy.prod 

    Python3

    import numpy

    n=5

    x=numpy.prod([i for i in range(1,n+1)])

    print(x)

    Output 

    120

    Time Complexity: O(n)
    Auxiliary Space: O(1)