我正在尝试计算一个大数,这需要BigInteger.Pow(),但我需要指数也是一个BigInteger而不是int.
即
BigInteger.Pow(BigInteger)
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
编辑:我想出了一个答案.用户狗帮助我实现了这一目标.
public BigInteger Pow(BigInteger value, BigInteger exponent)
{
BigInteger originalValue = value;
while (exponent-- > 1)
value = BigInteger.Multiply(value, originalValue);
return value;
}
Run Code Online (Sandbox Code Playgroud)
仅从一般数学的角度来看,这没有意义.这就是它没有实现的原因.
想想这个例子:你的BigInteger数字是2,你需要加强它1024.这意味着结果是一个1 KB的数字(2 ^ 1024).现在想象一下int.MaxValue:然后,你的号码已经消耗了2 GB的内存.使用a BigInteger作为指数将产生超出内存容量的数字!
如果你的应用程序需要这个数字的数字,数字本身对你的记忆来说太大了,你可能想要一个单独存储数字和指数的解决方案,但这是我只能推测的,因为它不是你问题的一部分.
如果您的问题是指数变量是a BigInteger,则可以将其强制转换为int:
BigInteger.Pow(bigInteger, (int)exponent); // exponent is BigInteger
Run Code Online (Sandbox Code Playgroud)
Pow(2, int64.MaxValue) 需要 1,152,921 TB 来保存数字,以实现规模感。但无论如何,这里有这个功能,以防你有一台非常好的电脑。
static BigInteger Pow(BigInteger a, BigInteger b) {
BigInteger total = 1;
while (b > int.MaxValue) {
b -= int.MaxValue ;
total = total * BigInteger.Pow(a, int.MaxValue);
}
total = total * BigInteger.Pow(a, (int)b);
return total;
}
Run Code Online (Sandbox Code Playgroud)