Friday, 26 May 2017

Factorial of number in Java

Factorial of number in Java.


Factorial of number in Java. Factorial of number is product of a number and all number below it. Example: 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.

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.


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();
 }

}



You may also like to see


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