Python факториал без цикла

Python – Factorial of a Number

Factorial of a Number can be calculated in many ways. Some of them are by using a for loop, or using a recursion function or a while loop.

In the following Python Factorial Examples, we will find factorial of a given whole number, using the above said procedures.

Problem Statement – Factorial of a Number

Factorial of a number n is given by,

0! = 1 1! = 1 2! = 2*1 = 2 3! = 3*2*1 = 6 4! = 4*3*2*1 = 24

Examples

1. Factorial using For Loop and Range

In the following example, we shall use Python For Loop to find Factorial. For a range(1,n+1) of given n, multiply the element over each iteration and return the result after coming out of the loop.

Python Program

def factorial(n): result = 1 for i in range(1,n+1): result = result*i return result n = 4 result = factorial(n) print(n,'! = ',result,sep="")

We have not validated if the number is negative. You may write the validation to check if the number is not negative and then proceed with finding the factorial.

2. Factorial using Recursive Function

Recursive functions are popular among budding programmers. But when it comes to performance, recursion is not a preferable choice in Python.

Python Program

# Recursion function to find factorial of a number n def factorial(n): if n < 0: print('Invalid number to find factorial.') elif n==1 or n==0 : return 1 else : return n * factorial(n - 1); # Take a number n = 10 # Call recursion function result = factorial(n) # Print result print(result)

3. Factorial using While Loop

We shall use Python While Loop in this solution of finding factorial of a number.

Python Program

#function computes factorial of a given number def factorial(n): result = 1 i=1 while i

Summary

In this tutorial of Python General Programs, we learned different ways to write a Python Program to compute factorial of a given number.

Источник

How to compute the factorial of a number in Python

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

The factorial(!) of a number n is the product of all positive numbers less than or equal to n.

Equation

The factorial of a number is defined as:

f a c t o r i a l ( n ) = n ∗ f a c t o r i a l ( n − 1 ) factorial(n)=n * factorial(n-1) f a c t or ia l ( n ) = n ∗ f a c t or ia l ( n − 1 )

f a c t o r i a l ( n ) = n ∗ ( n − 1 ) ∗ ( n − 2 ) . . . ∗ 1 factorial(n)=n * (n-1) * (n-2) . * 1 f a c t or ia l ( n ) = n ∗ ( n − 1 ) ∗ ( n − 2 ) . ∗ 1

Note: The factorial of 0 is 1.

Example

To calculate the factorial of 4, have a look at the following illustration:

4 ! = 4 ∗ 3 ∗ 2 ∗ 1 4 != 4*3*2*1 4 ! = 4 ∗ 3 ∗ 2 ∗ 1

Approaches to compute the factorial of a number in Python

In Python, there are two approaches to computing the factorial of a number:

Iterative Method

The following code explains how to compute the factorial of a number using the iterative approach:

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

The iterative approach works by setting a base value to 1 1 1 . For each loop, the method multiplies to the base value until the for loop finishes and you get the final factorial value.

Recursive approach

The recursive approach is when the function calls itself again and again until some stopping condition. It has two parts:

Base case

This is where the recursion stops

Recursive Case

This is the case where the function calls itself again and again until the base condition is reached.

f a c t o r i a l ( 4 ) = 4 ∗ f a c t o r i a l ( 3 ) factorial(4)=4*factorial(3) f a c t or ia l ( 4 ) = 4 ∗ f a c t or ia l ( 3 )

f a c t o r i a l ( 3 ) = 3 ∗ f a c t o r i a l ( 2 ) factorial(3)=3*factorial(2) f a c t or ia l ( 3 ) = 3 ∗ f a c t or ia l ( 2 )

f a c t o r i a l ( 2 ) = 2 ∗ f a c t o r i a l ( 1 ) factorial(2)=2*factorial(1) f a c t or ia l ( 2 ) = 2 ∗ f a c t or ia l ( 1 )

f a c t o r i a l ( 1 ) = 1 ∗ f a c t o r i a l ( 0 ) factorial(1)=1*factorial(0) f a c t or ia l ( 1 ) = 1 ∗ f a c t or ia l ( 0 )

The following illustration explains how to compute the factorial of a number using recursion in Python:

Источник

Python Factorial Examples

Python Factorial

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.

Recursion Stack

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.

References

Источник

3 способа вычислить факториал в Python

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. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Источник

Читайте также:  Учитель по html кодами
Оцените статью