VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-for-factorial-of-a-number/

⇱ Factorial of a Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Factorial of a Number

Last Updated : 9 Apr, 2026

Given a non-negative integers n, compute the factorial of the given number. Factorial of n is defined as n * (n -1) * (n - 2) * ... * 1. For n = 0, the factorial is defined as 1.

Examples:

Input: n = 5
Output: 120
Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120

Input: n = 4
Output: 24
Explanation: 4! = 4 * 3 * 2 * 1 = 24

Input: n = 0
Output: 1

Input: n = 1
Output: 1

Iterative Solution - O(n) Time and O(1) Space

Factorial is computed by multiplying all integers from 1 to n using a loop. We initialize a variable ans as 1 and update it in each iteration by multiplying with the current number. This approach avoids recursion and uses constant extra space.

Step-by-step execution:

For n = 4

  • Initialize : ans = 1
  • i = 1, ans = 1 * 1 = 1
  • i = 2, ans = 1 * 2 = 2
  • i = 3, ans = 2 * 3 = 6
  • i = 4, ans = 6 * 4 = 24

Final factorial = 24


Output
120

Recursive Solution - O(n) Time and O(n) Space

Factorial is defined recursively as n! = n × (n - 1)!. We define a base case where if n equals 0 or 1, the function returns 1. Otherwise, the function calls itself with n minus 1, breaking the problem into smaller subproblems until reaching the base case.

👁 dsa
Function Call for Factorial of 5

Output
120
Comment