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.

Java Code:

https://gist.github.com/thmain/33f2e9a7ee6c36e3168b97de80feb13e

Output:

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

Iterative Solution:

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

Java Code:

https://gist.github.com/thmain/469886811d1d86a9214a6cc35c699783

Output:

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