Home > Language Specific > BigInteger – Dealing with huge numbers. (Explained with factorial 500)

BigInteger – Dealing with huge numbers. (Explained with factorial 500)

Alrighty! So we are deviating away a bit from algorithms but I need to write a post on this to go on to explain one of the questions from this year’s ICPC Amritapuri Online Round. I’ll be talking about BigIntegers in this one.

So tell me, what do you do when someone asks you to find the factorial of 500. Most of you will write a factorial program in C++ with long long as your data type and then try to run it for 500. It is then that you realize the factorial of 500 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 in Java or BigNum in Python. I’ll show you a simple code in Java for calculating the factorial of 500 using BigInteger (Java).

import java.lang.*;

import java.math.*;

import java.io.*;

import java.util.*;

class WhateverYourFileName{

public static void main(String args[])

{

BigInteger number = new BigInteger(“500”);

BigInteger fact = new BigInteger(“1”);

while(!number.equals(BigInteger.ZERO)

{

fact=fact.multiply(number);

number=number.subtract(BigInteger.ONE);

}

System.out.println(fact);

}

}

Yes, as simple as that! For more details about BigInteger, you can visit the documentation here. No worries about huge numbers now, eh?! Enjoy with your newfound wisdom! 🙂

Advertisements
  1. October 17, 2011 at 12:26 am

    Again Big Integer. Duh.. Seems like they have one every year. Had one in my time too. But the program gave errors during comparison or something

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: