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:


public class FactorialRecursion {
public static int factorial(int num){
if(num==0)
return 1;
return num * factorial(num1);
}
public static void main(String[] args) {
int num = 10;
int fact = factorial(num);
System.out.println("Factorial of a number: " + num + " is(Recursion): " + fact);
}
}

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:


public class FactorialIterative {
public static int factorial(int num){
if(num==0)
return 1;
int result = 1;
for (int i = 2; i <=num ; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int num = 7;
int fact = factorial(num);
System.out.println("Factorial of a number: " + num + " is(Iterative): " + fact);
}
}

Output:

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.