【问题标题】:How to optimize programm to calculate catalan numbers如何优化程序以计算加泰罗尼亚语数
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 2016-04-06
      相关资源
      最近更新 更多