Improve Article
Save Article
Like Article
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
На чтение 3 мин Просмотров 4.7к. Опубликовано 28.02.2023
Содержание
- Введение
- Вычисление факториала циклом while
- Цикл while
- Цикл for
- Вычисление факториала Рекурсией
- Вычисление факториала методом factorial()
- Заключение
Введение
В ходе статьи рассмотрим 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. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂
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
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
- Overlapping sub-problems
- 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.
Вычисление факториала
Вводится натуральное число. Вычислить его факториал.
Решение задачи на языке программирования Python
Факториалом числа называют произведение всех натуральных чисел до него включительно. Например, факториал числа 5 равен произведению 1 * 2 * 3 * 4 * 5 = 120.
Формула нахождения факториала:
n! = 1 * 2 * … * n,
где n – это число, а n! – факториал этого числа.
Формулу можно представить в таком виде:
n! = 1 * … * (n-2) * (n-1) * n,
т. е. каждый предыдущий множитель меньше на единицу, чем последующий. Или в перевернутом виде, когда каждый следующий меньше предыдущего на единицу:
n! = n * (n-1) * (n-2) * … * 1,
Для вычисления факториала с помощью цикла можно использовать любую формулу. Для рекурсивного вычисления используется вторая.
Вычисление факториала с помощью циклов
С помощь цикла while
:
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
Больше задач в PDF