Factorial of a large number using BigInteger in Java

To calculate the factorial of a large number in Java we are going to use BigInteger. For the easy understanding, we have provided an easy example.

BigInteger class in Java is used for mathematical calculations of very large integer values. It belongs to java.math package. Primitive data types like int, long cannot store very big integer values. But there is no theoretical limit for BigInteger on the range of integer values. For example, the factorial of 100 has 158 digits which cannot be stored in any of the primitive data types. This large number can be stored in BigInteger. Therefore, BigInteger is very useful and is used a lot in competitive programming.

Find factorial of a large Number in Java

In this Java tutorial, we will learn

  • declaration of a BigInteger variable
  • initialization of BigInteger variables
  • mathematical operations
  • Factorial problem using BigInteger

 Declaration of BigInteger in Java

BigInteger d, e;    //Declaration

Initialization of BigInteger in Java

BigInteger a = new BigInteger("123");   //Initialization from string
BigInteger b= BigInteger.valueOf(52643643);  // Initialization through integer or long
BigInteger c= BigInteger.ONE;      //Initialization from BigInteger class constants



Mathematical operations

There are lots of mathematical functions in BigInteger class. Some functions are

  • add()
  • subtract()
  • multiply()
  • abs()
  • min()


d = new BigInteger("1");
e = BigInteger.TEN;
d = d.multiply(e);

String str= "57312975971";
long a= 868565523l;
BigInteger b= BigInteger.valueOf(a);
BigInteger c= b.add(new BigInteger(str));



Extraction of value from BigInteger

int x = A.intValue(); // value should be in limit of int x

long y = A.longValue(); // value should be in limit of long y

String z = A.toString();


if (A.compareTo(B) < 0) {}

if (A.equals(B)) {}

We can now solve the problem of factorial using BigInteger.

Factorial using BigInteger

import java.math.BigInteger;

public class BI {
    public static void main(String[] args) {


    public static BigInteger factorial(int N)
        BigInteger f = new BigInteger("1");

        for (int i = 2; i <= N; i++)
            f = f.multiply(BigInteger.valueOf(i));

        return f;




You can also read:

Leave a Reply

Your email address will not be published. Required fields are marked *