Calculate factorial in python

Calculate Factorial in Python

In this article we will discuss how to calculate a factorial in Python.

Table of Contents

Introduction

Most often you would see factorials in combinatorics algebra and probability theory.

Factorials are used in permutations (calculating the number of ways to arrange some objects) and combinations (calculating the number of ways a subset of objects can be selected from a set of objects).

Factorial formula

Basically, for any integer n, that is greater than or equal to 1 (\(n \geq 1\)), the factorial is the product of all integers in range \((1:n)\) and is denoted by \(n!\).

For example, the factorial of 5 would be:

Calculating factorial in Python

With the following steps we will create a program to calculate the factorial in Python:

Step 1: Get user input

Similarly to solving quadratic equation using Python, the first step is to obtain some user input. In this case, we would need a user to enter an integer for which the factorial should be calculated:

Of course, in this step a user can input any data type they want. There are some rules for the factorial calculation that we need to check for:

Let’s add these checks to the user input code:

=1: check_input = False else: print("Please make sure the input is an integer greater or equal to 1") check_input = True 

Step 2: Calculate factorial in Python

Now we know the \(n\) value and can continue with the factorial calculation.

Recall that the formula calculates the product of every integer in range \(n:1\), which means that integer \(i_ = i_t – 1\). To do this in Python we will simply run a for loop through every \(i_t\) value:

Here we start with an initial factorial value f = 1. We need to define a variable to do the calculations, and since the operation is multiplication, f=1 doesn’t change the final result of the calculation.

Then we basically multiply the starting value by each integer in the range. As an example, if we set \(n = 5\), then range(5, 1, -1) would be [5, 4, 3, 2, 1]. And the calculation would look like:

Running the above program for \(n = 5\) should have the result equal to 120.

Factorial functions in Python

The math library (prebuilt in Python) has a function to calculate factorial. The result would be the same as in the code in the above section but will only take one line to calculate it.

You can use the user input code from the previous section to get the \(n\) value from the user and use the factorial() function to calculate the factorial.

Читайте также:  Python from import разница

Conclusion

In this article we covered how you can calculate factorial in Python with math library.

Источник

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

Факториалом числа называют произведение всех натуральных чисел до него включительно. Например, факториал числа 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:

  1. Вызов функции fac(5)
  2. fac(5) вызывает fac(4)
  3. fac(4) вызывает fac(3)
  4. fac(3) вызывает fac(2)
  5. fac(2) вызывает fac(1)
  6. fac(1) возвращает в fac(2) число 1
  7. fac(2) возвращает в fac(3) число 1 * 2, т. е. 2
  8. fac(3) возвращает в fac(4) число 2 * 3, т. е. 6
  9. fac(4) возвращает в fac(5) число 6 * 4, т. е. 24
  10. fac(5) возвращает число 24 * 5, т. е. 120 в основную ветку программы
  11. Число 120 выводится на экран

Функция factorial модуля math

Модуль math языка программирования Python содержит функцию factorial , принимающую в качестве аргумента неотрицательное целое число и возвращающую факториал этого числа:

>>> import math >>> math.factorial(4) 24

Источник

Calculate a Factorial With Python — Iterative and Recursive

By definition, a factorial is the product of a positive integer and all the positive integers that are less than or equal to the given number. In other words, getting a factorial of a number means to multiply all whole numbers from that number, down to 1.

0! equals 1 as well, by convention.

A factorial is denoted by the integer and followed by an exclamation mark.

5! denotes a factorial of five.

And to calculate that factorial, we multiply the number with every whole number smaller than it, until we reach 1:

Keeping these rules in mind, in this tutorial, we will learn how to calculate the factorial of an integer with Python, using loops and recursion. Let’s start with calculating the factorial using loops.

Calculating Factorial Using Loops

We can calculate factorials using both the while loop and the for loop. The general process is pretty similar for both. All we need is a parameter as input and a counter.

Let’s start with the for loop:

def get_factorial_for_loop(n): result = 1 if n > 1: for i in range(1, n+1): result = result * i return result else: return 'n has to be positive' 

You may have noticed that we are counting starting from 1 to the n , whilst the definition of factorial was from the given number down to 1. But mathematically:

$$
1 * 2 * 3 * 4 . * n = n * (n-1) * (n-2) * (n-3) * (n-4) . * (n — (n-1))
$$

To simplify, (n — (n-1)) will always be equal to 1.

That means that it doesn’t matter in which direction we’re counting. It can start from 1 and increase towards the n , or it can start from n and decrease towards 1. Now that’s clarified, let’s start breaking down the function we’ve just wrote.

Читайте также:  Пример использования PHP

Our function takes in a parameter n which denotes the number we’re calculating a factorial for. First, we define a variable named result and assign 1 as a value to it.

Why assign 1 and not 0 you ask?

Because if we were to assign 0 to it then all the following multiplications with 0, naturally would result in a huge 0.

Then we start our for loop in the range from 1 to n+1 . Remember, the Python range will stop before the second argument. To include the last number as well, we simply add an additional 1 .

Inside the for loop, we multiply the current value of result with the current value of our index i .

Finally, we return the final value of the result . Let’s test our function print out the result:

inp = input("Enter a number: ") inp = int(inp) print(f"The result is: ") 

If you’d like to read more about how to get user input, read our Getting User Input in Python.

It will prompt the user to give input. We’ll try it with 4 :

Enter a number: 4 The result is: 24 

You can use a calculator to verify the result:

4! is 4 * 3 * 2 * 1 , which results 24.

Now let’s see how we can calculate factorial using the while loop. Here’s our modified function:

def get_factorial_while_loop(n): result = 1 while n > 1: result = result * n n -= 1 return result 

This is pretty similar to the for loop. Except for this time we’re moving from n towards the 1, closer to the mathematical definition. Let’s test our function:

inp = input("Enter a number: ") inp = int(inp) print(f"The result is: ") 

We’ll enter 4 as an input once more:

Enter a number: 4 The result is: 24 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Although the calculation was 4 * 3 * 2 * 1 the final result is the same as before.

Calculating factorials using loops was easy. Now let’s take a look at how to calculate the factorial using a recursive function.

Calculating Factorial Using Recursion

A recursive function is a function that calls itself. It may sound a bit intimidating at first but bear with us and you’ll see that recursive functions are easy to understand.

In general, every recursive function has two main components: a base case and a recursive step.

Base cases are the smallest instances of the problem. Also a break, a case that will return a value and will get out of the recursion. In terms of factorial functions, the base case is when we return the final element of the factorial, which is 1.

Without a base case or with an incorrect base case, your recursive function can run infinitely, causing an overflow.

Recursive steps — as the name implies- are the recursive part of the function, where the whole problem is transformed into something smaller. If the recursive step fails to shrink the problem, then again recursion can run infinitely.

Consider the recurring part of the factorials:

In other words 5! is 5 * 4! , and 4! is 4 * 3! and so on.

So we can say that n! = n * (n-1)! . This will be the recursive step of our factorial!

A factorial recursion ends when it hits 1. This will be our base case. We will return 1 if n is 1 or less, covering the zero input.

Let’s take a look at our recursive factorial function:

def get_factorial_recursively(n): if n 1: return 1 else: return n * get_factorial_recursively(n-1) 

As you see the if block embodies our base case, while the else block covers the recursive step.

inp = input("Enter a number: ") inp = int(inp) print(f"The result is: ") 

We will enter 3 as input this time:

Enter a number:3 The result is: 6 

We get the same result. But this time, what goes under the hood is rather interesting:

You see, when we enter the input, the function will check with the if block, and since 3 is greater than 1, it will skip to the else block. In this block, we see the line return n * get_factorial_recursively(n-1) .

We know the current value of n for the moment, it’s 3 , but get_factorial_recursively(n-1) is still to be calculated.

Then the program calls the same function once more, but this time our function takes 2 as the parameter. It checks the if block and skips to the else block and again encounters with the last line. Now, the current value of the n is 2 but the program still must calculate the get_factorial_recursively(n-1) .

So it calls the function once again, but this time the if block, or rather, the base class succeeds to return 1 and breaks out from the recursion.

Following the same pattern to upwards, it returns each function result, multiplying the current result with the previous n and returning it for the previous function call. In other words, our program first gets to the bottom of the factorial (which is 1), then builds its way up, while multiplying on each step.

Also removing the function from the call stack one by one, up until the final result of the n * (n-1) is returned.

This is generally how recursive functions work. Some more complicated problems may require deeper recursions with more than one base case or more than one recursive step. But for now, this simple recursion is good enough to solve our factorial problem!

If you’d like to learn more about recursion in Python, read our Guide to Understanding Recursion in Python!

Conclusion

In this article, we covered how to calculate factorials using for and while loops. We also learned what recursion is, and how to calculate factorial using recursion.

If you’ve enjoyed the recursion and want to practice more, try calculating the Fibonacci sequence with recursion! And if you have any questions or thoughts about our article, feel free to share in the comment section.

Источник

Оцените статью