How to calculate factorial of large number in Java?

Problem Description :

Write a program in Java that calculates factorial of a large number.

Concept :

The factorial of non-negative integer is denoted by n! and it is the product of all positive integers less than or equal to n.  For example - 5! = 5 X 4 X 3 X 2 X 1 = 120.
For calculating factorial, we are using BigInteger class that is present in java.math.* package.

Java Program :

package com.javamultiplex.number;

import java.math.BigInteger;
import java.util.Scanner;

 * @author Rohit Agarwal
 * @category Number Problems
 * @problem How to calculate factorial of large number?
public class FactorialOfLargeNumber {

 public static void main(String[] args) {

  Scanner input = null;
  try {
   input = new Scanner(;
   System.out.println("Enter number : ");
   int num = input.nextInt();
   BigInteger result = getFactorial(num);
   System.out.println("Factorial is : " + result);
  } finally {
   if (input != null) {


 private static BigInteger getFactorial(int num) {

  // Converting int to String.
  String number = String.valueOf(num);
  // Converting String to BigInteger.
  BigInteger n = new BigInteger(number);
  // ZERO=0
  BigInteger ZERO = BigInteger.ZERO;
  // ONE=1
  BigInteger ONE = BigInteger.ONE;
  // fact=1
  BigInteger fact = BigInteger.ONE;
  // while(n!=0)
  while (!(n.equals(ZERO))) {
   // fact=fact*n
   fact = fact.multiply(n);
   // n=n-1
   n = n.subtract(ONE);
  return fact;


Output :

Output of Java program that calculates factorial of a very large number.
Output - How to calculate factorial of a very large number in Java?

References :

Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.

Tags : Calculate factorial in Java, Solution in Java, large number, BigInteger, if else statement, while loop, String.

About Author:

I am simple guy with lot of ambitions. My main motive is to share whatever knowledge I have related to programming. With me you can easily learn how to solve any programming problem in Java.You can connect with me on social networking sites also.

Let's Get Connected: Linkedin | Facebook |

How to calculate factorial of large number in Java? How to calculate factorial of large number in Java? Reviewed by Rohit Agarwal on 12/28/2016 Rating: 5

No comments:

Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.

Powered by Blogger.