Advantage of BigInteger over long and int
Posted by Qingfeng Yang* Filled under keyword biginteger,data type,factorial
By Qingfeng Yang(Philadelphia, Pennsylvania | Computer Software)
In this tutorial we will see the scenerio where BigInteger holds advantage over using int or long
* Java int and long have a low limit when it comes to big number computation.
* For example, if we were to calculate the factorial of 100, (seems easy right?)
* We'll go above the limit of long and certainly int as well.
* Int in Java can only goes as high as 12!
* Long in Java goes as high as 20!
* For big number computations, Java provides the BigInteger/BigDecimal class.
** @author Qingfeng Yang
public class Factorial
public static void main(String args)
System.out.println("correct "+factorial(new BigInteger("100")));
System.out.println("Definitely incorrect "+factorial(100L));
//only goes to 12!
public static int factorial(int i)
int a = 1;
while (i > 1)
a *= i;
//only goes to 20!
public static long factorial(long i)
long a = 1;
while (i > 1)
a *= i;
public static BigInteger factorial(BigInteger b)
BigInteger a = BigInteger.ONE;
while (b.compareTo(BigInteger.ONE) > 0)
a = a.multiply(b);
b = b.subtract(BigInteger.ONE);
We have made a simple factorial program.
Here, we have three methods named factorial with different argument types ie method overloading
The first method computes factorial for integer value.
The second method computes factorial for long value.
The third method computes factorial for BigInteger value.
Now ,we all know that int has smaller limit than long.
If we check we can only calculate upto 12! making use of int.
After that we can use long. But the problem is long will also work upto 20!
After this limit we need to make use of BigInteger.
We can calculate factorial as high as 100! with BigInteger easily.
In above program we first try to find factorial of integer 12 and we get correct result.
We try factorial 20(long) and factorial for 100(BigInteger), in these we get correct result.
However when we try to calculate factorial 13(integer),21(long),100(long) we get wrong result.
So when we are dealing with limits above long just make use of BigInteger.
Hope you liked it.. :)
Now you can also share your java tricks with the world. Just write to us at firstname.lastname@example.org
Page 1 of 1 1
Please login to add your comments