3

我是一个经验不足的编码员,我需要为每个单值计算两个加泰罗尼亚语序列的乘积,然后总结这些乘积。n05000

该代码当前输出正确的答案,但需要 2.9-3.3 秒才能运行n-value 为5000. 我的目标是让代码每次在 3 秒内运行,所以我需要获得大约半秒的时间。

计算中的最大数字 ( 10,000!) 超过35,000位数,因此int不能long用于任何较重的计算,也不能使用任何外部库,这几乎让我剩下BigInteger.

通过测试,我发现下面显示for-loopsum()内容是迄今为止完成时间最长的(约 85% 的运行时间),因此这可能是最需要提高性能的地方。任何关于如何优化它的提示都值得赞赏。

// For all n-values
for (int k=0; k < n/2 + rest; k++) {
    result = result.add(catalan(k).multiply(catalan(n-k)));
}

这是整个代码:

import java.math.BigInteger;
import java.util.Scanner;

public class FactorialSum {

    static BigInteger[] bigInt;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            int n = sc.nextInt();

            // Creates a new array and initializes the default values
            bigInt = new BigInteger[n*2+1];
            bigInt[0] = BigInteger.ONE;
            if (n > 0)
                bigInt[1] = BigInteger.ONE;

            calcFactorials(n);

            // Calculates and prints the results
            System.out.println(sum(n));
        } finally {
            sc.close();
        }
    }

    // Calculates and stores all the factorials up to and including the specified n-value
    private static void calcFactorials(int n) {
        for (int factor = 2; factor <= n*2; factor++) {
            bigInt[factor] = bigInt[factor-1].multiply(BigInteger.valueOf(factor));
        }
    }

    // Calculates the catalan number using the binomial coefficient for the
    // specified n-value
    private static BigInteger catalan(int n) {
        BigInteger binomial = bigInt[n*2].divide(bigInt[n].pow(2));
        BigInteger cn = binomial.divide(BigInteger.valueOf(n+1));
        return cn;
    }

    // Calculates the sum for the specified range 0-n
    private static BigInteger sum(int n) {
        if (n > 0) {
            BigInteger result = BigInteger.ZERO;
            int rest = n % 2;

            // For all n-values
            for (int k=0; k < n/2 + rest; k++) {
                result = result.add(catalan(k).multiply(catalan(n-k)));
            }
            result = result.multiply(BigInteger.valueOf(2));

            // For even n-values
            if (rest == 0) {
                BigInteger lastNumber = catalan(n/2);
                result = result.add(lastNumber.pow(2));
            }
            return result;
        } else {
            return BigInteger.ONE;
        }
    }
}
4

1 回答 1

5

我需要为 0 到 5000 之间的每个 n 值计算两个加泰罗尼亚语序列的乘积,然后总结这些乘积。

好吧,这正是加泰罗尼亚数的另一种定义。

C n+1 = SUM i=0..n ( C i * C n-i )

所以,你基本上需要的是计算 C 5001。为了快速计算它,您可以使用另一个递归关系:

C n+1 = 2*(2n+1) / (n+2) * C n

这是程序:

public static void main(String[] args) {
    int n = 5000;

    BigInteger Cn = BigInteger.ONE;
    for (int i = 0; i <= n; i++) {
        Cn = Cn.multiply(BigInteger.valueOf(4 * i + 2)).divide(BigInteger.valueOf(i + 2));
    }

    System.out.println(Cn);
}

在我的笔记本电脑上工作不到 0.04 秒。享受!

于 2017-12-27T16:40:38.810 回答