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
 System.out.println(a);
BigInteger b= BigInteger.valueOf(52643643);  // Initialization through integer or long
System.out.println(b);
BigInteger c= BigInteger.ONE;      //Initialization from BigInteger class constants
System.out.println(c);

Output:

123
52643643
1

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);
System.out.println(d);

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

Output:

10
58181541494

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

Comparison

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) {

          System.out.println(factorial(100));
    }

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

Output:

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

 

You can also read:

Leave a Reply

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