- Вычисление факториала
- Вычисление факториала с помощью циклов
- Нахождение факториала рекурсией
- Функция factorial модуля math
- 3 способа вычислить факториал в Python
- Введение
- Вычисление факториала циклом while
- Цикл while
- Цикл for
- Вычисление факториала Рекурсией
- Вычисление факториала методом factorial()
- Заключение
- Python Factorial Examples
- The Python Factorial function
- Using math.factorial()
- Using an Iterative Procedure
- Using a Recursive Procedure
- Tail Recursive Calls
- Conclusion
- References
Вычисление факториала
Факториалом числа называют произведение всех натуральных чисел до него включительно. Например, факториал числа 5 равен произведению 1 * 2 * 3 * 4 * 5 = 120.
Формула нахождения факториала:
n! = 1 * 2 * … * n,
где n – это число, а n! – факториал этого числа.
Формулу можно представить в таком виде:
т. е. каждый предыдущий множитель меньше на единицу, чем последующий. Или в перевернутом виде, когда каждый следующий меньше предыдущего на единицу:
Для вычисления факториала с помощью цикла можно использовать любую формулу. Для рекурсивного вычисления используется вторая.
Вычисление факториала с помощью циклов
n = int(input()) factorial = 1 while n > 1: factorial *= n n -= 1 print(factorial)
Вычисление факториала с помощью цикла for :
n = int(input()) factorial = 1 for i in range(2, n+1): factorial *= i print(factorial)
Нахождение факториала рекурсией
def fac(n): if n == 1: return 1 return fac(n - 1) * n print(fac(5))
Поток выполнения программы при n = 5:
- Вызов функции fac(5)
- fac(5) вызывает fac(4)
- fac(4) вызывает fac(3)
- fac(3) вызывает fac(2)
- fac(2) вызывает fac(1)
- fac(1) возвращает в fac(2) число 1
- fac(2) возвращает в fac(3) число 1 * 2, т. е. 2
- fac(3) возвращает в fac(4) число 2 * 3, т. е. 6
- fac(4) возвращает в fac(5) число 6 * 4, т. е. 24
- fac(5) возвращает число 24 * 5, т. е. 120 в основную ветку программы
- Число 120 выводится на экран
Функция factorial модуля math
Модуль math языка программирования Python содержит функцию factorial , принимающую в качестве аргумента неотрицательное целое число и возвращающую факториал этого числа:
>>> import math >>> math.factorial(4) 24
3 способа вычислить факториал в Python
Статьи
Введение
В ходе статьи рассмотрим 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. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂
Python Factorial Examples
In this article, we’ll look at how we can calculate the Python factorial using different approaches.
The Python Factorial function
The Python factorial function factorial(n) is defined for a whole number n . This computes the product of all terms from n to 1 . factorial(0) is taken to be 1 .
factorial(n) = n * (n-1) * (n-2) * . * 1, n >= 1 factorial(n) = 1, n = 0
Therefore, factorial(4) = 4 * 3 * 2 * 1 = 24.
Let’s analyze how we can write this mathematical function in Python.
Using math.factorial()
We can directly use the math module’s factorial function to do the work for using:
import math def factorial(x): return math.factorial(x) print(factorial(5))
We’ll also look at finding this function using other methods: let’s use an iterative procedure now.
Using an Iterative Procedure
We can directly loop over all the numbers for 1 to n and directly multiply the product.
def factorial(n): if n == 0: return 1 prod = 1 for i in range(1, n+1): prod = prod * i return prod if __name__ == '__main__': print(factorial(4)) print(factorial(7))
Let’s now look at using a recursive method for the Python factorial function.
Using a Recursive Procedure
We can utilize recursion, to compute this function. Basically, we reduce this function into a smaller sub-problem. After we compute the sub-problems, we can combine the results to give the final answer.
Since the problem structure is a decreasing product, we can model the recursion in the following manner:
factorial(n) = n * factorial(n-1), n >= 1 factorial(0) = 1, n = 0
The last line is the base case. This is the point where the recursion stops, and we can get the final product, when the recursion unwinds.
We’ll write the corresponding Python function for this:
def factorial(n): if n == 0: # Base case n = 0 return 1 else: # Use the definition of factorial function return n * factorial(n-1) if __name__ == '__main__': print(factorial(4)) print(factorial(7))
That seems to be correct. Let’s analyze what actually happens in the recursion calls.
Whenever recursion calls are used, there is a call stack, which continuously stores the state of the program, until the base case is reached. The stack elements are finally popped out one by one after a value is returned by the corresponding block, when the recursion unwinds from n = 0 .
The whole process is explained in the below figure, for finding fact(3) . The first part of the entire process is the build-up of the stack where each of those recursive calls is stacked on top of each other until the function returns 1.
Once the function can no longer recursively call, it starts calculating the factorial as demonstrated below.
When the functions return, the stack elements get popped out one by one, from the top. When it finally reaches the main() stack, the function is finally complete, and we have our value, which comes out to be 6 .
Tail Recursive Calls
While our program works fine, the problem with our recursive function is that the stack size grows as much as the input size.
So if n is a very large number, our recursion stack may be very large, that that may cause the stack to overflow! To avoid this, we’ll use another approach to coding a recursive function, called a tail-recursive procedure.
The tail procedure call aims to perform the recursion call after computing the intermediate result. So, instead of increasing the stack size, the program can use the same stack for the whole process! It only needs to be updated.
This means that our recursive call must always be at the end. This is why it is a “tail call”.
def fact_helper(accum, n): if n == 0: return accum return fact_helper(accum*n, n-1) def factorial(n): return fact_helper(1, n) if __name__ == '__main__': print(factorial(4)) print(factorial(7))
Since we cannot directly make the recursive call at the end, we do it with another helper function, that does that actual computation for us. This helper function stores an accumulator , which stores the current value of the function.
The trick is to pass the accumulator as a parameter to the recursive function, and update it, using accum*n . This way, we will store the intermediate state in one variable, and hence, only in one stack frame!
You get the same output as before! Now, you’ve also ensured that the program uses only one stack frame, so it is essentially equivalent to the iterative procedure! Isn’t that nice?
Conclusion
In this article, we learned about how we can implement the factorial function in different ways, using the math module, as well as through both iteration and recursion.