示例#1
0
        static bigInt GCD(bigInt a, bigInt b)
        {
            if (a.equalToZero() || b.equalToZero())
            {
                return(a + b);
            }
            string bits = "1";
            bigInt gcd  = new bigInt(bits);

            while (a._bits[a._length - 1] == '0' && b._bits[b._length - 1] == '0')
            {
                a   = a >> 1;
                b   = b >> 1;
                gcd = gcd << 1;
            }
            while (!a.equalToZero())
            {
                while (a._bits[a._length - 1] == '0')
                {
                    a = a >> 1;
                }
                while (b._bits[b._length - 1] == '0')
                {
                    b = b >> 1;
                }
                bigInt t;
                if (a > b)
                {
                    t = a - b;
                }
                else
                {
                    t = b - a;
                }
                t = t >> 1;
                if (a > b || a == b)
                {
                    a = t;
                }
                else
                {
                    b = t;
                }
            }
            if (a._length > b._length)
            {
                gcd = gcd >> b._length;
            }
            else
            {
                gcd = gcd >> a._length;
            }
            gcd = bigInt.standardize(gcd);
            return(gcd);
        }
示例#2
0
        static bigInt powerMod(bigInt x, bigInt p, bigInt n)
        {
            //Return: result = (x ^ p) % n
            x = x % n;
            String bits   = "1";
            bigInt result = new bigInt(bits);

            // if (p == 0) return 1;
            if (p.equalToZero())
            {
                return(result);
            }
            else
            {
                //Cach 1:
                //bigInt a = new bigInt(x._bits);
                //if (p._bits[p._length - 1] == '1') result = x;
                //for (int i = 1; i < p._length; i++)
                //{
                //    a = mulMod(a, a, n);
                //    if (p._bits[p._length - 1 - i] == '1') result = mulMod(result, a, n);
                //}

                //Cach 2
                for (int i = 0; i < p._length; i++)
                {
                    result = mulMod(result, result, n);
                    if (p._bits[i] == '1')
                    {
                        result = mulMod(result, x, n);
                    }
                }
            }
            result = bigInt.standardize(result);
            return(result);
        }