Search code examples
javafactoriallargenumber

Find factorial of large numbers in Java


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.


Solution

  • public static void main(String[] args) {
        BigInteger fact = BigInteger.valueOf(1);
        for (int i = 1; i <= 8785856; i++)
            fact = fact.multiply(BigInteger.valueOf(i));
        System.out.println(fact);
    }