C# Pow(BigInteger,BigInteger)?
我试图计算一个大数字,这需要C# Pow(BigInteger,BigInteger)?,c#,biginteger,C#,Biginteger,我试图计算一个大数字,这需要biginger.Pow(),但我需要指数也是biginger,而不是int i、 e 我怎样才能做到这一点 编辑:我想出了一个答案。用户帮助我实现了这一点 public BigInteger Pow(BigInteger value, BigInteger exponent) { BigInteger originalValue = value; while (exponent-- > 1) value = BigInteger
biginger.Pow()
,但我需要指数也是biginger
,而不是int
i、 e
我怎样才能做到这一点
编辑:我想出了一个答案。用户帮助我实现了这一点
public BigInteger Pow(BigInteger value, BigInteger exponent)
{
BigInteger originalValue = value;
while (exponent-- > 1)
value = BigInteger.Multiply(value, originalValue);
return value;
}
仅仅从普通数学的角度来看,这是没有意义的。这就是为什么它没有实施 想想这个例子:你的
biginger
数字是2,你需要将它增加1024。这意味着结果是一个1KB的数字(2^1024)。现在,假设您使用int.MaxValue
:那么,您的号码将消耗2GB内存。使用BigInteger
作为指数将产生一个超出内存容量的数字
如果您的应用程序需要这种规模的数字,而数字本身对于您的内存来说太大,您可能需要一个单独存储数字和指数的解决方案,但这是我只能推测的,因为这不是您问题的一部分
如果您的问题是指数变量是
BigInteger
,您可以将其强制转换为int:
BigInteger.Pow(bigInteger, (int)exponent); // exponent is BigInteger
正如其他人所指出的,将某物提升到高于
int
容量的功率是个坏消息。但是,假设您意识到这一点,并且刚刚以BigInteger
的形式给出了指数,您可以将其转换为int
,然后继续您的快乐之路:
BigInteger.Pow(myBigInt, (int)myExponent);
或者,甚至更好
try
{
BigInteger.Pow(myBigInt, (int)myExponent);
}
catch (OverflowException)
{
// Do error handling and stuff.
}
Pow(2,int64.MaxValue)需要1152921TB的容量才能容纳这个数字,以达到规模感。不过,如果你有一台非常好的电脑,这就是它的功能
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;
}
我想到了:
public BigInteger Pow(BigInteger value, BigInteger exponent)
{
BigInteger originalValue = value;
while (exponent-- > 1)
value = BigInteger.Multiply(value, originalValue);
return value;
}
对我来说,解决方案是使用函数biginger.ModPow(biginger value,biginger index,biginger modules),因为我需要在之后进行修改 该函数计算一个给定的BigInteger与另一个BigInteger的幂,并用第三个bitineger计算模。 虽然它仍然需要大量的CPU功率,但可以对其进行评估,因为函数已经知道模,因此可以节省大量内存 希望这能帮助一些人解决同样的问题 编辑:
从.Net Framework 4.0开始提供,并且是.Net标准1.1及以上版本。你确定需要这么大的数字吗?重复的我同意@RufusL,
int
最多支持20亿,你真的需要筹集20亿的资金吗?@Matthew Yes。20亿不足以计算它。我已经编辑了你的标题。请参见“”,其中共识是“不,他们不应该”。当然,如果他有一个biginger
值恰好小于20亿,他可以在将其传递给pow
之前将其向下转换为Int32
,如果这是他的问题。这个数字太大,无法使用int。要计算的大数字的示例:Googlepex不能作为数字存储在内存中。它会消耗超出想象的内存(10^100字节)。你需要这些数字做什么?为什么不能“理论上”处理它们而不是实际存储这些数字?Googol是10^100。但是Googolplex是10^10^100。因此,它不能简单地计算。那么,你回答了你自己的问题;)你很有趣:D也许在一千年后,有人会偶然发现这篇文章,并嘲笑我们只有几场RAM…当我尝试使用这种方法时,我得到了抛出“System.OutOfMemoryException”类型的异常。我可以在不引发异常的情况下执行该操作吗?具有1位内存的计算机可以存储0到1之间的数字,具有100位内存的计算机可以存储0到(2^100)-1之间的数字。您可以计算的最大数字大约是Pow(2位可用)。因此,如果没有足够的内存,上述函数将无法运行,因此“System.OutOfMemoryException”exception.1152921 TB对于任何人都应该足够了。对于大于long.MaxValue
的数字,运行此方法需要多长时间?
public BigInteger Pow(BigInteger value, BigInteger exponent)
{
BigInteger originalValue = value;
while (exponent-- > 1)
value = BigInteger.Multiply(value, originalValue);
return value;
}