0

I have to write a programm that calculates the catalan numbers and therefor I hava to calculate some factorials. The Problem is that the programm needs to be able to process inputs of up to 5000 and also has certain time limits that have to be fullfilled. I used the BigInteger class to be able to process these big numbers, but now it takes too long. I do not know how to optimize the programm further.

Here is my Code to calculate the factorials:

public static BigInteger factorial(BigInteger toFactorial) 
{
    if(toFactorial.intValue() <= 1) 
    {
        return new BigInteger("1");
    }
        
    return toFactorial.multiply(factorial(toFactorial.subtract(new BigInteger("1"))));
}

and here is how i use these to calculate the catalan numbers:

for(int i = 0; i < anzCases; i++)
{
    BigInteger x = new BigInteger(io.getWord());
    BigInteger facX = factorial(x);
    BigInteger facXPlus1 = facX.multiply(x.add(new BigInteger("1")));           
    System.out.println( factorial( x.multiply( new BigInteger("2") ) ).divide( facXPlus1.multiply( facX ) ) );
}

In this case x is the input. Thanks for your help.

Tobias
  • 41
  • 2
  • 8

1 Answers1

0

There are constants, use BigInteger.ONE, and your own constants.

Use a factorial for long upto some limit of BigInteger.

Apply math intelligence. The most fruitful, but requires applied mathematics.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138