java中与BigInteger的组合
我正在做一个作业,我必须实现一种递归方法来计算两个数字的组合。例如,java中与BigInteger的组合,java,combinations,biginteger,Java,Combinations,Biginteger,我正在做一个作业,我必须实现一种递归方法来计算两个数字的组合。例如,5C3将是10。也就是说,总共5个对象中有3个对象的10个组合。但是,我想实现一种使用BigInteger类的方法,以便可以计算更大的组合,例如2400 pick 3。出于某种原因,我的代码仍然返回一个负数,很像是正则整数时的行为。我在下面包含了我的代码。有人能告诉我哪里出了问题吗 import java.math.BigInteger; public class Combination { public static Big
5C3
将是10
。也就是说,总共5个对象中有3个对象的10个组合。但是,我想实现一种使用BigInteger类的方法,以便可以计算更大的组合,例如2400 pick 3。出于某种原因,我的代码仍然返回一个负数,很像是正则整数时的行为。我在下面包含了我的代码。有人能告诉我哪里出了问题吗
import java.math.BigInteger;
public class Combination {
public static BigInteger[][] memo = new BigInteger[3000][3000];
public static BigInteger choose(BigInteger n, BigInteger k) {
if (n.intValue() == 0 && k.intValue() > 0) {
return BigInteger.ZERO;
} else if (k.intValue() == 0 && n.intValue() >= 0) {
return BigInteger.ONE;
} else if (memo[n.intValue()][k.intValue()] != null) {
return memo[n.intValue()][k.intValue()];
} else {
memo[n.intValue()][k.intValue()] = choose(n.subtract(BigInteger.ONE), k.subtract(BigInteger.ONE)).add(choose(n.subtract(BigInteger.ONE), k));
}
return memo[n.intValue()][k.intValue()];
}
public static void main(String args[]) {
if (args.length < 1) {
System.out.println("Usage: java Combination <N> <K>");
System.exit(0);
}
int H = Integer.parseInt(args[0]);
int R = Integer.parseInt(args[1]);
BigInteger N = BigInteger.valueOf(H);
BigInteger K = BigInteger.valueOf(R);
System.out.println(choose(N, K).intValue());
}
import java.math.biginger;
公共类组合{
公共静态BigInteger[]memo=新的BigInteger[3000][3000];
公共静态BigInteger选择(BigInteger n,BigInteger k){
如果(n.intValue()==0&&k.intValue()>0){
返回biginger.ZERO;
}else if(k.intValue()==0&&n.intValue()>=0){
返回BigInteger.1;
}else if(备注[n.intValue()][k.intValue()]!=null){
返回备忘录[n.intValue()][k.intValue()];
}否则{
备注[n.intValue()][k.intValue()]=choose(n.subtract(biginger.ONE),k.subtract(biginger.ONE)).add(choose(n.subtract(biginger.ONE),k));
}
返回备忘录[n.intValue()][k.intValue()];
}
公共静态void main(字符串参数[]){
如果(参数长度<1){
System.out.println(“用法:java组合”);
系统出口(0);
}
inth=Integer.parseInt(args[0]);
intr=Integer.parseInt(args[1]);
BigInteger N=BigInteger.valueOf(H);
BigInteger K=BigInteger.valueOf(R);
System.out.println(选择(N,K).intValue());
}
}
应该是
System.out.println(choose(N, K).toString());
应该是
System.out.println(choose(N, K).toString());
检查另一种实现组合运算的方法,而不使用可能溢出整型/长型变量最大值的许多乘法:我删除了我的答案。我错了。你说的负值是2400和3吗?检查另一种实现组合运算的方法,而不使用可能溢出整型/长型变量最大值的乘法:我删除了我的答案。我错了。你说的负值是2400和3?+1。应该是这样。我看错了地方,看错了方向。整数溢出。哇,非常感谢。你不知道这有多大帮助。现在是凌晨1点,我思考这个问题已经有一段时间了。再次感谢+1.应该是这样。我看错了地方,看错了方向。整数溢出。哇,非常感谢。你不知道这有多大帮助。现在是凌晨1点,我思考这个问题已经有一段时间了。再次感谢!