BigInteger.sqrt C# (CSharp) Method

sqrt() public method

public sqrt ( ) : BigInteger
return BigInteger
        public BigInteger sqrt()
        {
                uint numBits = (uint)this.bitCount();

                if((numBits & 0x1) != 0)        // odd number of bits
                        numBits = (numBits >> 1) + 1;
                else
                        numBits = (numBits >> 1);

                uint bytePos = numBits >> 5;
                byte bitPos = (byte)(numBits & 0x1F);

                uint mask;

                BigInteger result = new BigInteger();
                if(bitPos == 0)
                        mask = 0x80000000;
                else
                {
                        mask = (uint)1 << bitPos;
                        bytePos++;
                }
                result.dataLength = (int)bytePos;

                for(int i = (int)bytePos - 1; i >= 0; i--)
                {
                        while(mask != 0)
                        {
                                // guess
                                result.data[i] ^= mask;

                                // undo the guess if its square is larger than this
                                if((result * result) > this)
                                        result.data[i] ^= mask;

                                mask >>= 1;
                        }
                        mask = 0x80000000;
                }
                return result;
        }

Usage Example

Ejemplo n.º 1
0
        public void TestSqrt()
        {
            BigInteger bi;
            int        val, sqrtVal;
            Random     rand = new Random();

            for (int i = 0; i < 100; i++)
            {
                val     = rand.Next();
                bi      = new BigInteger(val);
                sqrtVal = (int)Math.Floor(Math.Sqrt(val));
                Assert.AreEqual(sqrtVal, bi.sqrt());
            }

            bi = new BigInteger();
            Assert.AreEqual(0, bi.sqrt());

            bi = new BigInteger("48234798239584935745984795837", 10);
            Assert.AreEqual(219624220521291, bi.sqrt());

            bi = new BigInteger("4823479823958493574598479580945895480904590958034958034580948509485094850934095809458408509485094850948509803459834037", 10);
            Assert.AreEqual("69451276618637425696010359184467375646677653070095660334837", bi.sqrt().ToString());

            bi = new BigInteger("902380594730957598498379487239749823749832749823749823759823759823649623984623974627682368236423764823649823749823749823794872398472398479238479382749823794823794823749823794823794872398479238479823749823749823749823749823749823740239480293840923804923804923809482304982", 10);
            Assert.AreEqual("949937153042746085485800690340716910200218535446376464883006159759187016711766033117259286191698487700345112712284215083646265481183724", bi.sqrt().ToString());
        }
All Usage Examples Of BigInteger::sqrt