Exemple #1
0
        public static BigInt operator /(BigInt N, BigInt D)
        {
            if (D == 0)
            {
                throw new DivideByZeroException();
            }
            if (N.Radix != D.Radix)
            {
                throw new Exception();
            }
            bool IsNegative = N.IsNeg ^ D.IsNeg;

            N = N.Abs();
            D = D.Abs();
            if (N < D)
            {
                return(new BigInt(0, N.Radix));
            }
            int    size = N.Data.Length - D.Data.Length + 1;
            int    pow  = D.Data.Length;
            BigInt x    = BigInt.DecToBin(N.Radix / (D.Data.Last() - '0'), N.Radix);

            x.Data = new string('0', size) + x.Data;
            BigInt two = BigInt.DecToBin(2, N.Radix);

            two.Data = new string('0', size + pow) + two.Data;
            BigInt prev;

            while (true)
            {
                prev   = x;
                x      = x * (two - D * x);
                x.Data = x.Data.Remove(0, size + pow);
                if (x == prev)
                {
                    break;
                }
            }
            BigInt Q = N * x;

            Q.Data = Q.Data.Remove(0, size + pow);
            if ((Q + new BigInt(1, Q.Radix)) * D <= N)
            {
                Q += new BigInt(1, Q.Radix);
            }
            Q.Data = RemoveZeros(Q.Data);
            return(IsNegative ? -Q : Q);
        }
Exemple #2
0
        static public BigInt FastPow(int a, int pow, int rad)
        {
            BigInt A   = new BigInt(a, rad);
            BigInt b   = new BigInt(1, rad);
            BigInt map = BigInt.DecToBin(pow, 2);

            for (int i = map.Data.Length - 1; i >= 0; i--)
            {
                b *= b;
                if (map.Data[i] == '1')
                {
                    b *= A;
                }
            }
            return(b);
        }