Be the first user to complete this post

  • 0
Add to List
Beginner

291. Find Factorial of a given Number

Objective: Given a number, write a program to find factorial of that number.

What is Factorial Number?

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. The value of 0! is 1, according to the convention for an empty product

N! = n*(n-1)*(n-2)*…..*2*1

Example:

5! = 5 x 4 x 3 x 2x 1 = 120
7! = 7 x 6 x 5 x 4 x 3 x 2x 1 = 5040

Approach:

Recursive Solution-

  • If number is 0, return 1.
  • Make a recursive call to get the result of number – 1.
  • Multiply number with the result of number – 1.

Output:

Factorial of a number: 10 is(Recursion): 3628800

Iterative Solution:

  • If the number is 0, return 1.
  • Run a loop from 2 to number and multiple all of them to get the result.

Output:

Factorial of a number: 7 is(Iterative): 5040