如何优化程序来计算加泰罗尼亚数

问题描述

我必须编写一个程序来计算加泰罗尼亚数,因此我需要计算一些阶乘。问题是该程序需要能够处理多达 5000 的输入,并且还具有必须完成的特定时间限制。我使用 BigInteger 类能够处理这些大数字,但现在它需要太长时间。我不知道如何进一步优化程序。

这是我计算阶乘的代码:

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

这是我如何使用这些来计算加泰罗尼亚数字:

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

在这种情况下,x 是输入。 感谢您的帮助。

解决方法

有常量,使用 BigInteger.ONE,还有你自己的常量。

长期使用阶乘,直至达到 BigInteger 的某个限制。

应用数学智能。最有成果,但需要应用数学。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...