tags:

views:

177

answers:

3

.NET 4.0 provides System.Numerics.BigInteger, I need to compute the square root(a reasonable aproximation atleast) of a BigInteger, as to not reimplement the wheel, does anyone have a nice extension methods for this ?

+3  A: 

The simplest feasible way to compute a square root to an arbitrary precision is probably Newton's method.

mquander
+1  A: 

Google(java biginteger sqrt) gives many hits which help. For instance http://www.merriampark.com/bigsqrt.htm

John
Porting this should be easy enough...but i don't think there's a `BigDecimal` Implementation for .NET (as of now). +1 anyway :)
st0le
+3  A: 

I am not sure if Newton's Method is the best way to compute bignum square roots, because it involves divisions which are slow for bignums. You can use a CORDIC method, which uses only addition and shifts (shown here for unsigned ints)

static uint isqrt(uint x)
{
    int b=15; // this is the next bit we try 
    uint r=0; // r will contain the result
    uint r2=0; // here we maintain r squared
    while(b>=0) 
    {
        uint sr2=r2;
        uint sr=r;
                    // compute (r+(1<<b))**2, we have r**2 already.
        r2+=(uint)((r<<(1+b))+(1<<(b+b)));      
        r+=(uint)(1<<b);
        if (r2>x) 
        {
            r=sr;
            r2=sr2;
        }
        b--;
    }
    return r;
}

There's a similar method which uses only addition and shifts, called 'Dijkstras Square Root', explained for example here:

Luther Blissett
This computes the integer square root of an integer. If you need decimals, you can pre-scale the operand.
Luther Blissett
@Luther: you can compute to arbitrary precision by continuing the loop for negative values of b and converting left shifts of -n to right shifts of n.
Chris Dodd