Find factorial of large numbers in Java

Himanshu Aggarwal picture Himanshu Aggarwal · Jul 12, 2012 · Viewed 28.2k times · Source

I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.

But it is displaying infinity as the result, may be because it is exceeding its limit.

So please guide me the way to find the factorial of a very large number.

My code:

class abc
{
    public static void main (String[]args)
    {
        double fact=1;
        for(int i=1;i<=8785856;i++)
        {
            fact=fact*i;
        }

        System.out.println(fact);
    }
}

Output:-

Infinity

I am new to Java but have learned some concepts of IO-handling and all.

Answer

ThePadawan picture ThePadawan · Jul 12, 2012

You might want to reconsider calculating this huge value. Wolfram Alpha's Approximation suggests it will most certainly not fit in your main memory to be displayed.