Question

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.

Was it helpful?

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);
}

OTHER TIPS

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.

This code should work fine :-

public class BigMath {
    public static String factorial(int n) {
        return factorial(n, 300);
    }

    private static String factorial(int n, int maxSize) {
        int res[] = new int[maxSize];
        res[0] = 1; // Initialize result
        int res_size = 1;

        // Apply simple factorial formula n! = 1 * 2 * 3 * 4... * n
        for (int x = 2; x <= n; x++) {
            res_size = multiply(x, res, res_size);
        }

        StringBuffer buff = new StringBuffer();
        for (int i = res_size - 1; i >= 0; i--) {
            buff.append(res[i]);
        }

        return buff.toString();
    }

    /**
     * This function multiplies x with the number represented by res[]. res_size
     * is size of res[] or number of digits in the number represented by res[].
     * This function uses simple school mathematics for multiplication.
     * 
     * This function may value of res_size and returns the new value of res_size.
     */
    private static int multiply(int x, int res[], int res_size) {
        int carry = 0; // Initialize carry.

        // One by one multiply n with individual digits of res[].
        for (int i = 0; i < res_size; i++) {
            int prod = res[i] * x + carry;
            res[i] = prod % 10; // Store last digit of 'prod' in res[]
            carry = prod / 10;  // Put rest in carry
        }

        // Put carry in res and increase result size.
        while (carry != 0) {
            res[res_size] = carry % 10;
            carry = carry / 10;
            res_size++;
        }

        return res_size;
    }

    /** Driver method. */
    public static void main(String[] args) {
        int n = 100;

        System.out.printf("Factorial %d = %s%n", n, factorial(n));
    }
}

Hint: Use the BigInteger class, and be prepared to give the JVM a lot of memory. The value of 8785856! is a really big number.

Use the class BigInteger. ( I am not sure if that will even work for such huge integers )

This blog post explains biginteger factorial in java with examples.

Infinity is a special reserved value in the Double class used when you have exceed the maximum number the a double can hold.

If you want your code to work, use the BigDecimal class, but given the input number, don't expect your program to finish execution any time soon.

The above solutions for your problem (8785856!) using BigInteger would take literally hours of CPU time if not days. Do you need the exact result or would an approximation suffice?

There is a mathematical approach called "Sterling's Approximation " which can be computed simply and fast, and the following is Gosper's improvement: enter image description here

 import java.util.*;
 import java.math.*;

class main
{
public static void main(String args[])
{
    Scanner sc= new Scanner(System.in);

        int i;
        int n=sc.nextInt();


      BigInteger fact = BigInteger.valueOf(1);

        for ( i = 1; i <= n; i++)
        {
            fact = fact.multiply(BigInteger.valueOf(i));
        }
        System.out.println(fact);

}
}

Try this:

import java.math.BigInteger;

public class LargeFactorial
{
    public static void main(String[] args)
    {
        int n = 50; 
    }
    public static BigInteger factorial(int n)
    {
       BigInteger result = BigInteger.ONE;
       for (int i = 1; i <= n; i++)
           result = result.multiply(new BigInteger(i + ""));
       return result;
    }
}
    Scanner r = new Scanner(System.in);
    System.out.print("Input Number : ");
    int num = r.nextInt();
    int ans = 1;
    if (num <= 0) {
        ans = 0;
    }
    while (num > 0) {
        System.out.println(num + " x ");
        ans *= num--;
    }
    System.out.println("\b\b=" + ans);
    public static void main (String[] args) throws java.lang.Exception
    {
        BigInteger fact= BigInteger.ONE;
        int factorialNo = 8785856 ;

        for (int i = 2; i <= factorialNo; i++) {
              fact = fact.multiply(new BigInteger(String.valueOf(i)));
        }

        System.out.println("Factorial of the given number is = " + fact);
     }

To really find out the factorial of this number you should use PYTHON functions , and try to open the task manager and see how much memory the compiler takes . After that you will know that how much time JVM is going to take ,as PYTHON is the best language for numerical calculations.

import java.util.Scanner;


public class factorial {
    public static void main(String[] args) {
        System.out.println("Enter the number : ");
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        factorial f=new factorial();
        int result=f.fact(n);
        System.out.println("factorial of "+n+" is "+result);
    }
    int fact(int a)
    {
        if(a==1)
            return 1;
        else
            return a*fact(a-1);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top