×

Algorithm for Factorial of a number in Python

What is a Factorial Number?

In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n.

For example, the factorial of 5 is denoted by 5! and it is equal to the product of 5, 4, 3, 2, and 1 i.e. 5*4*3*2*1 which is equal to 120. The factorial of 0, denoted by 0! is defined to be 1.

The factorial is used in various areas of mathematics, science, and engineering. It has several important properties, such as being equal to the number of ways to arrange a set of n distinct objects (a permutation of n objects), or the number of ways to select k objects from a set of n distinct objects (a combination of n objects taken k at a time).

In Python, you can compute the factorial of a number using a for loop or a recursive function. Here is an example of a for loop that calculates the factorial of a number:

def factorial(n):
result = 1
fori in range(1, n + 1):
result *= i
return result

This function takes a single integer n as input and returns the factorial of n. The function first initializes a variable result to 1. It then iterates over a range object that starts at 1 and ends at n + 1, and for each iteration, it multiplies the value of result by the loop variable and assigns the result back to result. Finally, the function returns result. You can also implement the factorial function using recursion.

What is Recursion?

Recursion is a programming technique in which a function calls itself with a modified input until it reaches a base case. Here is an example of a recursive function that calculates the factorial of a number:

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

This function takes a single integer n as input and returns the factorial of n. The function first checks if ‘n’ is 0. If it is, it returns 1. Otherwise, it returns the product of n and the factorial of n - 1. This function calls itself with a modified input (n - 1) until it reaches the base case (n == 0), at which point it returns 1.

Here is the simple algorithm for finding the factorial of a number in Python:

  • Define a function factorial (n) that takes in a single integer n.
  • If n is less than 0, return 0.
  • If n is 0 or 1, return 1.
  • Initialize a variable result to 1.
  • Iterate over a range object that starts at 2 and ends at n + 1. For each iteration, multiply the value of result by the loop variable and assign the result back to result.
  • Return result.

Here is the implementation of this algorithm in Python:

def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
result = 1
fori in range(2, n + 1):
result *= i
return result

You can test this function by calling it with different values of n.

Example:

import math
print(math.factorial(1))  
print(math.factorial(0))   
print(math.factorial(1))   
print(math.factorial(5))   
print(math.factorial(10))  

Output:

1
1
2
120
3628800

In addition to using a ‘for’ loop or a recursive function, you can also use Python's built-in math module to calculate the factorial of a number. The math module has a function called factorial that takes a single integer n as input and returns the factorial of n.

The math.factorial function raises a ValueError if you pass a negative integer to it. Otherwise, it returns the factorial of the given integer.

There are several ways to find the factorial of a number in Python. Here are a few of them:

1. Using a for loop:

def factorial(n):
result = 1
fori in range(1, n+1):
result *= i
return result

2. Using a while loop:

def factorial(n):
result = 1
i = 1
whilei<= n:
result *= i
i += 1
return result

3. Recursive function:

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

4. Using math.factorial method:

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

This method uses a closed-form expression to calculate the factorial in O(1) time.

5. Using reduce method from functools:

from functools import reduce
from operator import mul


def factorial(n):
return reduce(mul, range(1, n+1))

All of these methods give the correct factorial of a given number. Recursive method is easy to understand and implement, but a large input can cause a maximum recursion depth exceeded in comparison, while the last method (using reduce method) may be less readable but more performing on large inputs.


Related Topics

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Python Num2words

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.