java biginteger 运算_java-进行大量计算时提高性能(BigInteger)

我是一个经验不足的编码员,需要进行练习,我需要针对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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值