Monday, 12 December 2016

Factorial of Number using Recursion in Java

Find Factorial of Number. OR
Java Program to Find Factorial of Number. OR
Recursive Program to find Factorial of Number.


A factorial is a function that multiplies a number by every number below it.

Factorial of 5
5! = 5 * 4 * 3 * 2 * 1 = 120.

Factorial of 3
3! = 3 * 2 * 1 = 120.

Note: The value of 0! is 1

Below you can get Factorial of number till 20.
factorial of numbers from 1 to 20 chart
Factorial of numbers from 1 to 20 chart

Algorithm


Lets see algorithm for printing Factorial of a Number.

We will see 3 ways of finding Factorial of number,
  1. Recursive Implementation
  2. Iterative Implementation
  3. Using BigInteger for Large values.
Check Recursive Implementation Program flow below.


In case if you are still finding it difficult to understand, not to worry, lets walk through complete recursive call stack of Factorial of a number.

factorial of a number using recursion call stack
Factorial of a number using recursion

Java Program to Print Factorial of a number using Recursion.


package javabypatel;

import java.math.BigInteger;

public class FindFactorialOfNumber {

 public static void main(String[] args) {
  System.out.println(factRecursive(5));
  System.out.println(factIterative(5));
  System.out.println(factorialForLargeNumbers(5));
 }

 //Recursive Implementation
 private static int factRecursive(int num){
  if(num < 0){
   return -1;
  }

  if(num == 1 || num == 0){
   return 1;
  }
  num = num * factRecursive(num-1);
  return num; 
 }

 //Iterative Implementation
 private static int factIterative(int num){
  if(num < 0){
   return -1;
  }

  int fact = 1;
  for (int i = 1; i <= num; i++) {
   fact *= i;
  }
  return fact;
 }

 //Using BigInteger for Large values
 public static String factorialForLargeNumbers(int num) {
  if(num < 0){
   return "-1";
  }
  
  BigInteger fact = new BigInteger("1");
  
  for (int i = 1; i <= num; i++) {
   fact = fact.multiply(new BigInteger(String.valueOf(i)));
  }
  return fact.toString();
 }

}


Compress a given string in-place and with constant extra space.

Check whether a given string is an interleaving of String 1 and String 2.

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.

Serialize and Deserialize a Binary Tree

Advanced Multithreading Interview Questions In Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

No comments:

Post a Comment