Java 将bigInteger转换为integer的intValue()方法给出了错误的结果
此数组包含从0到1000003的整数的阶乘 我把X作为一个大整数变量,它来自模运算Java 将bigInteger转换为integer的intValue()方法给出了错误的结果,java,biginteger,Java,Biginteger,此数组包含从0到1000003的整数的阶乘 我把X作为一个大整数变量,它来自模运算 static BigInteger []fact = new BigInteger[1000003]; 现在,当我尝试“事实[X]”时,它在“事实[X]”处给出了这个错误: 将X更改为X.intValue()后,X的值将发生更改 如何访问事实[X]? 救命 数组索引应为整数。如果您使用的是fact[X],那么X必须是integer而不是biginger BigInteger cannot be convert
static BigInteger []fact = new BigInteger[1000003];
现在,当我尝试“事实[X]”时,它在“事实[X]”处给出了这个错误:
将X更改为X.intValue()后,X的值将发生更改
如何访问事实[X]?
救命 数组索引应为整数。如果您使用的是
fact[X]
,那么X必须是integer而不是biginger
BigInteger cannot be converted to int
temp = (fact[x].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);
如果x
和y
是biginger
BigInteger cannot be converted to int
temp = (fact[x].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);
到
您必须在
biginger
和int
或Integer
之间进行区分。biginger
和int
之间没有自动转换(自动装箱/取消装箱)。此外,对象数组的维数始终为int
。然后,每次要访问biginger
数组中的元素时,都必须显式地将索引值转换为int
,这可以通过调用biginger\intValue()
假设
x
和y
计算没有问题,我试图对您的代码进行注释。请注意,
biginger
数组在创建时仅包含null
引用。这意味着您需要先创建并设置数组元素,然后再尝试对其执行操作
temp = (fact[x.intValue()].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);
把你的问题读了5遍,但还是不明白,所以你想说你的数据成员
temp
是int
类型,你试图给它赋值biginger
一个完整的、可复制的测试用例。告诉我们你认为它的输出应该是什么,以及它实际上是什么。我投了反对票,因为描述没有清楚地说明问题中表达的陈述(这实际上不是一个问题)。我同意@JBNizet的评论。我不相信你的话,这个问题需要大编辑或者删除biginger.valueOf(3).intValue()
产生3
,而不是500002
。但是X.intValue()给出了不同的值如何分配X,y和mod的值??mod的值为1000003 X和y的值来自另一个模运算这就是我所做的。但是X.intValue()与X不同。如果没有计算X和y的代码,我们不能说。但是如果您测试biginger.valueOf(12345).intValue()==12345
,它应该是真的。请注意,x和y在您的程序中应始终<1000003
。
temp = (fact[x.intValue()].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);
final int max = 1000003;
BigInteger [] fact = new BigInteger[max];
BigInteger mod = BigInteger.valueOf(max);
BigInteger x = ...; // computed somewhere
BigInteger y = ...; // computed somewhere
BigInteger temp =
fact[x.intValue()] // x is a BI, take intValue() to access array element
.multiply( // operands are BI
fact[x.subtract(y) // operands are BI
.intValue()]) // take intValue() to access array
.mod(mod); // operands are BI, result is BI