我是一个经验不足的编码员,我需要为每个单值计算两个加泰罗尼亚语序列的乘积,然后总结这些乘积。n
0
5000
该代码当前输出正确的答案,但需要 2.9-3.3 秒才能运行n
-value 为5000
. 我的目标是让代码每次在 3 秒内运行,所以我需要获得大约半秒的时间。
计算中的最大数字 ( 10,000!
) 超过35,000
位数,因此int
不能long
用于任何较重的计算,也不能使用任何外部库,这几乎让我剩下BigInteger
.
通过测试,我发现下面显示for-loop
的sum()
内容是迄今为止完成时间最长的(约 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;
}
}
}