我是一个经验不足的编码员,需要进行练习,我需要针对0到5000之间的每个n值计算两个catalan sequences的乘积,然后总结这些乘积.
该代码当前输出正确的答案,但是运行n值为5000的过程需要花费2.9-3.3秒.我的目标是每次使代码在3秒内运行,因此我需要花费大约半秒钟的时间.
计算中的最大数字(10,000!)长超过35,000位,因此int或long不能用于任何较重的计算,我也不能使用任何外部库,这几乎让我留给了BigInteger.
通过测试,我发现sum()中的for循环是迄今为止完成时间最长的时间(约占运行时间的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;
}
}
}