static BigInteger []fact = new BigInteger[1000003];
此数组包含从 0 到 1000003 的整数阶乘
我有 X 作为来自模运算的大整数变量
while(m.compareTo(BigInteger.valueOf(0)) == 1 || n.compareTo(BigInteger.valueOf(0)) == 1){
if(m.compareTo(BigInteger.valueOf(0)) == 1 || m.compareTo(BigInteger.valueOf(0)) == 0)
{
x = m.mod(mod);
m = m.divide(mod);
}
现在,当我尝试"fact[X]">时,它会在"fact[X]"处给出此错误:
BigInteger cannot be converted to int
temp = (fact[x].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);
将 X 更改为 X.intValue(( 后,X 的值正在更改。
如何访问事实[X]?帮助!!
区分BigInteger
和int
或Integer
。BigInteger
和int
之间没有自动转换(自动装箱/拆箱(。此外,对象数组的维度始终是 int
.然后每次要访问BigInteger
数组中的元素时,都必须将索引值显式转换为int
,这是通过调用BigInteger#intValue()
来完成的。
我试图注释您的代码,假设x
和y
计算没有问题。
请注意,创建BigInteger
数组时,它仅包含null
引用。这意味着在尝试对其执行某些操作之前,您需要创建和设置数组元素。
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
数组索引应该是整数。如果您使用的是fact[X]
则 X 必须是整数而不是BigInteger
如果x
和y
BigInteger
,请更改此逻辑
temp = (fact[x].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);
自
temp = (fact[x.intValue()].multiply(fact[(x.subtract(y)).intValue()])).mod(mod);