×

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

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.