BigInteger.Pow(BigInteger,BigInteger)?

avi*_*i12 3 c# biginteger

我正在尝试计算一个大数,这需要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)

byt*_*e77 7

仅从一般数学的角度来看,这没有意义.这就是它没有实现的原因.

想想这个例子:你的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)

  • Googlepex无法作为数字存储在内存中.它会消耗超乎想象的内存(10 ^ 100字节).你需要那些数字,为什么不能"理论上"处理它们而不是实际存储数字? (2认同)
  • 那么,你回答了自己的问题;) (2认同)

dog*_*dog 5

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)

  • 你很有趣 :D 也许在一千年后,有人会偶然发现这篇文章并嘲笑我们只有几场 RAM... (2认同)
  • 1,152,921 TB 对任何人来说都足够了。 (2认同)