【发布时间】:2021-05-30 20:39:10
【问题描述】:
我必须编写一个计算加泰罗尼亚数字的程序,因此我必须计算一些阶乘。问题是程序需要能够处理多达 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 是输入。 感谢您的帮助。
【问题讨论】:
标签: java optimization catalan