问题描述
我必须编写一个程序来计算加泰罗尼亚数,因此我需要计算一些阶乘。问题是该程序需要能够处理多达 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 的某个限制。
应用数学智能。最有成果,但需要应用数学。