📔
Algorithms Analysis & Design
  • Algorithm Analysis & Design
  • 🚢Searching and Sorting
    • Introduction-Search
    • Linear Search
    • Binary Search
    • Interpolation Search
    • Introduction-Sorting
    • Bubble Sort
    • Selection Sort
    • Counting Sort
  • 💸Greedy Method
    • Introduction
    • Activity Selection
    • Fractional Knapsack Problem
    • Graph Colouring
  • 🚠Backtracking
    • Introduction
    • Hamiltonian Path/Cycle Problem
    • N Queen Problem
    • Rat in a Maze
    • Knight's Tour Problem
  • ⚔️Divide and Conquer
    • Introduction
    • Strassen's Matrix multiplication
    • Karatsuba algorithm
    • Tower of Hanoi
    • Closest Pair
  • 💣Dynamic Programming
    • Introduction
    • Longest Common Subsequence
    • Floyd-Warshall Algorithm
    • 0-1 Knapsack problem
    • Dice Throw
  • 📈Graph
    • Introduction
    • DFS
    • Dictionary Game
    • BFS
    • Flood Fill Algorithm
    • Minesweeper Lite
  • 🔢Number Theory
    • Introduction
    • GCD
    • Factorial
    • IsPrime | School Method
    • IsPrime | Fermat's Little Theorem
    • IsPrime | Miller-Rabin Method
  • 🌮References
Powered by GitBook
On this page

Was this helpful?

  1. Number Theory

Factorial

Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n.

For example factorial of 6 is

6*5*4*3*2*1 which is 720.

Recursive Solution: Factorial can be calculated using following recursive formula.

  n! = n * (n-1)!
  n! = 1 if n = 0 or n = 1

Factorial of 5 is 120

Iterative Solution: Factorial can also be calculated iteratively as recursion can be costly for large numbers. Here we have shown the iterative approach using both for and while loop.

Using For loop

#include <iostream>
using namespace std; 
// function to find factorial of given number
unsigned int factorial(unsigned int n)
{    
    int res = 1, i;
    for (i = 2; i <= n; i++)
        res *= i;
    return res;
} 
// Driver code
int main()
{    
    int num = 5;
    cout << "Factorial of "         << num << " is "         << factorial(num) << endl;
    return 0;
}

Output :

Factorial of 5 is 120

One line Solution :

#include <iostream>
using namespace std; 
int factorial(int n)
{    
// single line to find factorial
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);} 
// Driver Code
int main()
{
    int num = 5;
    cout << "Factorial of " << num << " is "<< factorial(num);
    return 0;
} 

Output:

Factorial of 5 is 120
PreviousGCDNextIsPrime | School Method

Last updated 3 years ago

Was this helpful?

🔢