Home > BigInteger > How to handle Huge numbers – BigInteger

How to handle Huge numbers – BigInteger

Online competition are becoming tougher and tougher and now most of the questions require to deal with number greater than the capacity of unsigned long long int
So whats the possible approach for this?

So tell me, what do you do when someone asks you to find the factorial of 100. Most of you will write a factorial program in C++ with long long as your data type and then try to run it for 100. It is then that you realize the factorial of 100 will be too large for any integer data type in C/C++. So unless you plan to store numbers in strings and manipulate then), you will have to go for BigInteger or BigDecimal in Java or BigInteger in C#.NET.

A simple program to show the working of BigInteger in JAVA

import java.math.BigInteger;
class Main
{
	public static void main(String args[])

		{
		BigInteger number = new BigInteger("100");
		BigInteger fact = new BigInteger("1");
		int t = 100;
		while(t-- > 0)
		{
			fact=fact.multiply(number);
			number=number.subtract(BigInteger.ONE);
		}
		System.out.println(fact);
	}
}

Some useful links
More details of BigInteger Class (JAVA) : http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html
More details of BigDecimal Class (JAVA) : http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html
More details of BigInteger Class (C#.NET) : http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx
Feel free to ask for your doubts or experiments. 🙂

  1. May 13, 2012 at 12:35 AM

    Ha! I remember when I learned Java just to be able to use the BigInt Class…The possibilities of Java are much more my friend.

    • May 13, 2012 at 9:55 AM

      BigInt and BigDecimal… some of the most awesomest classes of JAVA 😉
      yeah they are damn easy to use.
      After all I know HOW important they are to me… I hope you got my point 😛

  2. Kevin Patel
    May 16, 2012 at 12:36 AM

    One can also look into alternatives like Python, where arbitrary precision numbers are the norm. That way, the code becomes less language specific, and more logic oriented

    • May 16, 2012 at 12:38 AM

      Yup sir, I agree, but sometimes (1000)! is not possible with python, but works like a charm in java

  1. No trackbacks yet.

Leave a comment