计算一个BigInteger(System.Numerics.BigInteger)的平方根 [英] Calculate square root of a BigInteger (System.Numerics.BigInteger)
问题描述
.NET 4.0提供了 System.Numerics.BigInteger
键入任意-大的整数。我需要计算平方根(或一个合理的近似 - 例如,整数的平方根)的的BigInteger
。所以,我没有重新实现轮子,没有任何人有一个很好的扩展方法为这个?
.NET 4.0 provides the System.Numerics.BigInteger
type for arbitrarily-large integers. I need to compute the square root (or a reasonable approximation -- e.g., integer square root) of a BigInteger
. So that I don't have to reimplement the wheel, does anyone have a nice extension method for this?
推荐答案
的检查的BigInteger不是有code来计算的Java BigInteger的整数的平方根一个完美的正方形。这被翻译成C#,作为一个扩展的方法。
Check if BigInteger is not a perfect square has code to compute the integer square root of a Java BigInteger. Here it is translated into C#, as an extension method.
public static BigInteger Sqrt(this BigInteger n)
{
if (n == 0) return 0;
if (n > 0)
{
int bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(n, 2)));
BigInteger root = BigInteger.One << (bitLength / 2);
while (!isSqrt(n, root))
{
root += n / root;
root /= 2;
}
return root;
}
throw new ArithmeticException("NaN");
}
private static Boolean isSqrt(BigInteger n, BigInteger root)
{
BigInteger lowerBound = root*root;
BigInteger upperBound = (root + 1)*(root + 1);
return (n >= lowerBound && n < upperBound);
}
非正式测试表明,这是大约75X比的Math.sqrt慢,对于小的整数。该VS探查指向isSqrt乘法的热点。
Informal testing indicates that this is about 75X slower than Math.Sqrt, for small integers. The VS profiler points to the multiplications in isSqrt as the hotspots.
这篇关于计算一个BigInteger(System.Numerics.BigInteger)的平方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!