Как найти факториал в питоне программа

На чтение 3 мин Просмотров 4.6к. Опубликовано 28.02.2023

Содержание

  1. Введение
  2. Вычисление факториала циклом while
  3. Цикл while
  4. Цикл for
  5. Вычисление факториала Рекурсией
  6. Вычисление факториала методом factorial()
  7. Заключение

Введение

В ходе статьи рассмотрим 3 способа вычислить факториал в Python.

Вычисление факториала циклом while

Цикл while

Для начала дадим пользователю возможность ввода числа и создадим переменную factorial равную единице:

number = int(input('Введите число: '))
factorial = 1

Как мы знаем, факториал – это произведение натуральных чисел от единицы до числа n. Следовательно создадим цикл, который не закончится, пока введённое пользователем число больше единицы. Внутри цикла увеличиваем значение в переменной factorial умножая его на переменную number, после чего уменьшаем значение в number на единицу:

number = int(input('Введите число: '))
factorial = 1

while number > 1:
    factorial = factorial * number
    number = number - 1

print(factorial)

# Введите число: 10
# 3628800

Цикл for

Обычно способ нахождения факториала при помощи цикла for не рассматривается, но почему бы и нет. Принцип не сильно отличается от цикла while, просто приравниваем значение введённое пользователем к переменной factorial, а в цикле указываем количество итреаций начиная с единицы, и заканчивая введённым числом:

number = int(input('Введите число: '))
factorial = number

for i in range(1, number):
    factorial = factorial * i

print(factorial)

# Введите число: 5
# 120

Вычисление факториала Рекурсией

Для вычисления факториала про помощи рекурсии, создадим функцию factorial(), и в качестве аргумента передадим number:

Внутри функции добавим условие, что если переданное число в аргумент number равняется единице, то возвращаем его. Если же условие не сработало, то вернётся аргумент number умноженный на вызов функции factorial() с передачей аргумента number – 1:

def factorial(number):
    if number == 1:
        return number
    else:
        return number * factorial(number - 1)

Дадим пользователю возможность ввода, вызовем функцию и выведем результат в консоль:

def factorial(number):
    if number == 1:
        return number
    else:
        return number * factorial(number - 1)


print(factorial(int(input('Введите число: '))))

# Введите число: 7
# 5040

Вычисление факториала методом factorial()

В стандартном модуле math есть специальный метод для вычисления факториала под названием factorial(). Используем его для нахождения факториала:

from math import factorial

number = int(input('Введите число: '))

print(factorial(number))

# Введите число: 4
# 24

Заключение

В ходе статьи мы с Вами рассмотрели целых 3 способа вычислить факториал в Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Admin

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Not many people know, but python offers a direct function that can compute the factorial of a number without writing the whole code for computing factorial.

    Naive method to compute factorial

    Python3

    n = 23

    fact = 1

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

        fact = fact * i

    print("The factorial of 23 is : ", end="")

    print(fact)

    Output

    The factorial of 23 is : 25852016738884976640000
    

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

    Using math.factorial()

    This method is defined in “math” module of python. Because it has C type internal implementation, it is fast.

    math.factorial(x)
    Parameters :
    x : The number whose factorial has to be computed.
    Return value :
    Returns the factorial of desired number.
    Exceptions : 
    Raises Value error if number is negative or non-integral.

    Python3

    import math

    print("The factorial of 23 is : ", end="")

    print(math.factorial(23))

    Output

    The factorial of 23 is : 25852016738884976640000
    

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

    Exceptions in math.factorial()

    • If given number is Negative : 

    Python3

    import math

    print("The factorial of -5 is : ", end="")

    print(math.factorial(-5))

    Output:

    Traceback (most recent call last):
      File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in 
        print (math.factorial(-5))
    ValueError: factorial() not defined for negative values
    • If given number is Non – Integral Value : 

    Python3

    import math

    print("The factorial of 5.6 is : ", end="")

    print(math.factorial(5.6))

    Output:

    Traceback (most recent call last):
      File "/home/3987966b8ca9cbde2904ad47dfdec124.py", line 9, in 
        print (math.factorial(5.6))
    ValueError: factorial() only accepts integral values

    This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Last Updated :
    08 Dec, 2022

    Like Article

    Save Article

    For performance reasons, please do not use recursion. It would be disastrous.

    def fact(n, total=1):
        while True:
            if n == 1:
                return total
            n, total = n - 1, total * n
    

    Check running results

    cProfile.run('fact(126000)')
    

    4 function calls in 5.164 seconds
    

    Using the stack is convenient (like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.

    If the stack is high, it means that the computer stores a lot of information about function calls.

    The method only takes up constant memory (like iteration).

    Or using a ‘for’ loop

    def fact(n):
        result = 1
        for i in range(2, n + 1):
            result *= i
        return result
    

    Check running results

    cProfile.run('fact(126000)')
    

    4 function calls in 4.708 seconds
    

    Or using the built-in function math

    def fact(n):
        return math.factorial(n)
    

    Check running results

    cProfile.run('fact(126000)')
    

    5 function calls in 0.272 seconds
    

    Table of contents

        • What is Factorial?
        • Formula of Factorial
        • 10 Factorial
        • Factorial of 5
        • Factorial of 0
        • Factorial Program in Python
          • Factorial program in Python using the function
          • Factorial program in python using for loop
          • Factorial program in Python using recursion
        • Count Trailing Zeroes in Factorial using Python
        • Frequently asked questions

    What is Factorial?

    In simple words, if you want to find the factorial of a positive integer, keep multiplying it with all the positive integers less than that number. The final result that you get is the factorial of that number. So if you want to find the factorial of 7, multiply 7 with all positive integers less than 7, and those numbers would be 6,5,4,3,2,1. Multiply all these numbers by 7, and the final result is the factorial of 7.

    If you are looking to build your expertise in Python factorial program, consider getting certified. This free course on Factorial Program in Python offers you complete guidance on the subject and also a certificate on completion which is sure to make your CV stand out.

    Formula of Factorial

    Factorial of a number is denoted by n! is the product of all positive integers less than or equal to n:
    n! = n*(n-1)*(n-2)*…..3*2*1

    10 Factorial

    So what is 10!? Multiply 10 with all the positive integers which are less than 10.
    10! =10*9*8*7*6*5*4*3*2*1=3628800

    Factorial of 5

    To find ‘5!’ again, do the same process. Multiply 5 with all the positive integers less than 5. Those numbers would be 4,3,2,1
    5!=5*4*3*2*1=120

    Factorial of 0

    Since 0 is not a positive integer, as per convention, the factorial of 0 is defined to be itself.
    0!=1

    Factorial program in python

    Factorial of a number

    Computing this is an interesting problem. Let us think about why simple multiplication would be problematic for a computer. The answer to this lies in how the solution is implemented.

    1! = 1
    2! = 2
    5! = 120
    10! = 3628800
    20! = 2432902008176640000
    30! = 9.332621544394418e+157

    The exponential rise in the values shows us that factorial is an exponential function, and the time taken to compute it would take exponential time.

    Factorial Program in Python

    We are going to go through 3 ways in which we can calculate factorial:

    • Using a function from the math module
    • Iterative approach(Using for loop)
    • Recursive approach

    Factorial program in Python using the function

    This is the most straightforward method which can be used to calculate the factorial of a number. Here we have a module named math which contains several mathematical operations that can be easily performed using the module.

    import math
    num=int(input("Enter the number: "))
    print("factorial of ",num," (function): ",end="")
    print(math.factorial(num))

    TEST THE CODE

    Input – Enter the number: 4
    Output – Factorial of 4 (function):24

    Factorial program in python using for loop

    def iter_factorial(n):
        factorial=1
        n = input("Enter a number: ")
        factorial = 1
        if int(n) >= 1:
            for i in range (1,int(n)+1):
                factorial = factorial * i
            return factorial
      
    num=int(input("Enter the number: "))
    
    print("factorial of ",num," (iterative): ",end="")
    print(iter_factorial(num))

    TEST THE CODE

    Input – Enter the number: 5
    Output – Factorial of 5 (iterative) : 120

    Consider the iterative program. It takes a lot of time for the while loop to execute. The above program takes a lot of time, let’s say infinite. The very purpose of calculating factorial is to get the result in time; hence, this approach does not work for huge numbers.

    Factorial program in Python using recursion

    def recur_factorial(n):
        """Function to return the factorial
        of a number using recursion"""
        if n == 1:
            return n
        else:
            return n*recur_factorial(n-1)
    
    num=int(input("Enter the number: "))
    
    print("factorial of ",num," (recursive): ",end="")
    print(recur_factorial(num))

    TEST THE CODE

    Input – Input – Enter the number : 4
    Output – Factorial of 5 (recursive) : 24

    On a 16GB RAM computer, the above program could compute factorial values up to 2956. Beyond that, it exceeds the memory and thus fails. The time taken is less when compared to the iterative approach. But this comes at the cost of the space occupied.

    What is the solution to the above problem?
    The problem of computing factorial has a highly repetitive structure.

    To compute factorial (4), we compute f(3) once, f(2) twice, and f(1) thrice; as the number increases, the repetitions increase. Hence, the solution would be to compute the value once and store it in an array from where it can be accessed the next time it is required. Therefore, we use dynamic programming in such cases. The conditions for implementing dynamic programming are

    1. Overlapping sub-problems
    2. optimal substructure 

    Consider the modification to the above code as follows:

    def DPfact(N):
        arr={}
        if N in arr:
            return arr[N]
        elif N == 0 or N == 1:
            return 1
            arr[N] = 1
        else:
            factorial = N*DPfact(N - 1)
            arr[N] = factorial
        return factorial
        
    num=int(input("Enter the number: "))
    
    print("factorial of ",num," (dynamic): ",end="")
    print(DPfact(num))

    TEST THE CODE

    Input – Enter the number: 6
    Output – factorial of 6 (dynamic) : 720

    A dynamic programming solution is highly efficient in terms of time and space complexities.

    Count Trailing Zeroes in Factorial using Python

    Problem Statement: Count the number of zeroes in the factorial of a number using Python

    num=int(input("Enter the number: "))
      
    # Initialize result 
    count = 0
    # Keep dividing n by 
    # powers of 5 and 
    # update Count 
    temp = 5
    while (num / temp>= 1):
        count += int(num / temp) 
        temp *= 5
    
    # Driver program  
    print("Number of trailing zeros", count)

    Output
    Enter the Number: 5
    Number of trailing zeros 1

    Learn how to find if a string is a Palindrome.

    Learn how to print the Fibonacci Series in Python. Also, learn artificial intelligence online with the help of this AI Course.

    Frequently asked questions

    1. What is factorial in math?

    Factorial of a number, in mathematics, is the product of all positive integers less than or equal to a given positive number and denoted by that number and an exclamation point. Thus, factorial seven is written 4! meaning 1 × 2 × 3 × 4, equal to 24. Factorial zero is defined as equal to 1. The factorial of Real and Negative numbers do not exist.

    2. What is the formula of factorial?

    To calculate the factorial of a number N, use this formula:
    Factorial=1 x 2 x 3 x…x N-1 x N

    3. Is there a factorial function in Python?

    Yes, we can import a module in Python known as math which contains almost all mathematical functions. To calculate factorial with a function, here is the code:

    import math
    num=int(input(“Enter the number: “))
    print(“factorial of “,num,” (function): “,end=””)
    print(math.factorial(num))

    Found this blog interesting? Learn Artificial Intelligence Online with the help of Great Learning’s PGP Artificial Intelligence and Machine Learning course, and upskill today! While you’re at it, check out the python course for beginners to learn more about the basic Python.

    In this article, you’ll learn how to find the factorial of a number using different methods like…

    • Using for Loop
    • Using IF…else Statement
    • Using Recursion
    • Using math. factorial()

    Factorial of a Number using for Loop

    Let us take up the example of python code that takes a positive integer as input to determine the factorial of positive integers. In the following code, the loop begins with one, and then it multiplies by each number that precedes the actual number whose factorial is to be determined.

    The following python code illustrates the factorial function using a loop.

    Python code:

    print ("Input a number")
    factorialIP = int (input ())
    ffactor23 = 1
    for j in range (1, factorialIP+1):
       ffactor23 = ffactor23 * j
    print ("The factorial of the number is “, ffactor23)
    

    Output:

    Input a number
    4
    The factorial of the number is 24
    

    The above python program takes the input of positive numbers only, and it does not have a check of negative numbers in it. In this program, the factor is 1 when j is equal to 1. When j is 2, the factor is multiplied with 2, and it will do the action till j comes at 4 to arrive at 24.

    Factorial of a Number using IF…else Statement

    The following python code illustrates the factorial function using function. Let us take up the following python code that takes positive integers as input to determine the factorial of positive integers.

    In previous python code, the check for negative numbers was not applied, making the factorial function incomplete and prone to deliver an error message if negative numbers are put as an input.

    In the given code, the loop begins with one, and then it multiplies by each number that precedes the actual number whose factorial is to be determined, and the function also checks for negative numbers.

    Python code:

    print("Enter a number for the purpose of determining factorial")
    factorialIP = int(input())
    def factorial(factorialIP):
       if factorialIP < 0:
         print ('Factorial does not exist')
         factor=0
         return factor
       elif factorialIP == 0:
         factor=1
         return factor
         print(factor)
       else:
         factor = 1
         for j in range (1, factorialIP+1):
           factor = factor * j
         return factor
      print ("The factorial of the number is ", factorial(factorialIP))
    

    Output:

    1) Enter a number to determine factorial
       -4
       Factorial does not exist
       The factorial of the number is 0
    
    2) Enter a number to determine factorial
       4
       Factorial does not exist
       The factorial of the number is 24
    

    The above python program to find factorial of a number takes the input of positive numbers only, and it does have a check of negative numbers in it using the if and else statement of python. In this program, the factor is 1 when j equals 1. When j is 2, the factor is multiplied with 2, and it will do the action till j comes at 4 to arrive at 24.

    Factorial of a Number using Recursion

    The following python code illustrates the factorial function using recursion. Let us take up the following python code that takes positive integers as input to determine the factorial of positive integers. In this example, a recursive function determines the factorial number.

    Python code:

    print("Enter a number for the purpose of determining factorial")
    def factorial(num2):
      if num2 < 0:
        return 'Factorial does not exist'
      elif num2 == 0:
         return 1
      else:
         return num2 * factorial(num2-1)
    number1 = int(input())
    print("The factorial of the number is",factorial(number1))
    

    Output: –

    Enter a number for the purpose of determining factorial
    4
    The factorial of the number is 24
    

    The recursion can be explained as a concept wherein the function invoked in the python module can call itself again and again. It runs until the time the python condition present in the python module is satisfied, wherein the function invoked is passed with value.

    In the above python program, the function number def factorial keeps calling itself recursively until and unless the number reaches zero. Once the number reaches zero, it initializes the number as 1, ending the recursion.

    The following python code illustrates the factorial function using math.factorial(), which can be used by importing the math module.

    This function does not accept negative integers, and it throws an error message of value error when float numbers are provided. Let us take up the following python code that takes positive integers as input to determine the factorial of positive integers.

    Python code:

    print("Enter a number for computing factorial")
    import math
    number1 = int(input())
    print("The factorial is as computed comes out to be ")
    print(math.factorial(number1))
    

    Output: –

    Enter a number for computing factorial
    4
    The factorial, as computed, comes out to be 24
    

    Algorithm for the Factorial Program in Python

    Let us take an example that illustrates the concept of factorial.

    For determination of factorial 5, follow the following steps: –

    5! = 5 x (5-1) x (5-2) x (5-3) x (5-4)
    5! =120
    

    Here, 5! is expressed as 120.

    The following diagram helps in understanding the algorithm of computing factorial, and in this case, let us take an example of factorial 4!

    Algorithm cum pictorial example of factorial 4!

    Algorithm cum pictorial example of factorial 4!

    Application of Factorial in Python

    Factorial of a number has a wide level of applications in mathematics. Here are important applications of Python:

    • The python helps in computation, followed with print factorial in faster and more efficient terms than other available programming languages.
    • The python code is easily understandable and can be replicated across different platforms, and the factorial python program can be incorporated in several mathematical model-building assignments.

    Summary:

    • Factorial of a number can be described as the product or multiplication of all positive integers equal to or less than the number for which the product or factorial is being determined.
    • There are three ways in which the factorial of a number in python can be executed.
      1. Factorial computation using For Loop
      2. Factorial computation using recursion.
      3. Usage of user-defined function
    • The factorial of a number is determined for a non-negative integer, and the results are always in positive integers.
    • By exception of the rule, a zero factorial is at 1.
    • Factorial of a number has a wide level of applications in mathematics.

    Learn our next tutorial about Swap two numbers without using a third variable

    Понравилась статья? Поделить с друзьями:
  • Как найти реквизиты по исполнительному листу
  • Сбой при копировании файлов загрузки windows 10 в командной строке как исправить
  • Как найти длину хорды примеры
  • Как найти точку минимума функции пример
  • Как найти корабль края в minecraft