コード例 #1
0
        public static BigInteger DivideAndRemainder(BigInteger dividend, BigInteger divisor, out BigInteger remainder)
        {
            int divisorSign = divisor.Sign;

            if (divisorSign == 0)
            {
                // math.17=BigInteger divide by zero
                throw new ArithmeticException(Messages.math17);                 //$NON-NLS-1$
            }
            int divisorLen = divisor.numberLength;

            int[] divisorDigits = divisor.digits;
            if (divisorLen == 1)
            {
                var values = Division.DivideAndRemainderByInteger(dividend, divisorDigits[0], divisorSign);
                remainder = values[1];
                return(values[0]);
            }

            int[] thisDigits = dividend.digits;
            int   thisLen    = dividend.numberLength;
            int   cmp        = (thisLen != divisorLen)
                                ? ((thisLen > divisorLen) ? 1 : -1)
                                : Elementary.CompareArrays(thisDigits, divisorDigits, thisLen);

            if (cmp < 0)
            {
                remainder = dividend;
                return(BigInteger.Zero);
            }
            int thisSign        = dividend.Sign;
            int quotientLength  = thisLen - divisorLen + 1;
            int remainderLength = divisorLen;
            int quotientSign    = ((thisSign == divisorSign) ? 1 : -1);

            int[] quotientDigits  = new int[quotientLength];
            int[] remainderDigits = Division.Divide(quotientDigits, quotientLength,
                                                    thisDigits, thisLen, divisorDigits, divisorLen);

            var quotient = new BigInteger(quotientSign, quotientLength, quotientDigits);

            remainder = new BigInteger(thisSign, remainderLength, remainderDigits);
            quotient.CutOffLeadingZeroes();
            remainder.CutOffLeadingZeroes();

            return(quotient);
        }
コード例 #2
0
ファイル: BigInteger.cs プロジェクト: bugbit/algebra
 /// <inheritdoc cref="IComparable{T}.CompareTo"/>
 public int CompareTo(BigInteger other)
 {
     if (sign > other.sign)
     {
         return(GREATER);
     }
     if (sign < other.sign)
     {
         return(LESS);
     }
     if (numberLength > other.numberLength)
     {
         return(sign);
     }
     if (numberLength < other.numberLength)
     {
         return(-other.sign);
     }
     // Equal sign and equal numberLength
     return(sign * Elementary.CompareArrays(digits, other.digits,
                                            numberLength));
 }
コード例 #3
0
ファイル: BigInteger.cs プロジェクト: bugbit/algebra
        private static bool TryParse(string s, int radix, out BigInteger value, out Exception exception)
        {
            if (String.IsNullOrEmpty(s))
            {
                exception = new FormatException(Messages.math11);
                value     = null;
                return(false);
            }
            if ((radix < CharHelper.MIN_RADIX) || (radix > CharHelper.MAX_RADIX))
            {
                // math.11=Radix out of range
                exception = new FormatException(Messages.math12);
                value     = null;
                return(false);
            }

            int sign;

            int[] digits;
            int   numberLength;
            int   stringLength = s.Length;
            int   startChar;
            int   endChar = stringLength;

            if (s[0] == '-')
            {
                sign      = -1;
                startChar = 1;
                stringLength--;
            }
            else
            {
                sign      = 1;
                startChar = 0;
            }

            /*
             * We use the following algorithm: split a string into portions of n
             * char and convert each portion to an integer according to the
             * radix. Then convert an exp(radix, n) based number to binary using the
             * multiplication method. See D. Knuth, The Art of Computer Programming,
             * vol. 2.
             */

            try
            {
                int charsPerInt          = Conversion.digitFitInInt[radix];
                int bigRadixDigitsLength = stringLength / charsPerInt;
                int topChars             = stringLength % charsPerInt;

                if (topChars != 0)
                {
                    bigRadixDigitsLength++;
                }
                digits = new int[bigRadixDigitsLength];
                // Get the maximal power of radix that fits in int
                int bigRadix = Conversion.bigRadices[radix - 2];
                // Parse an input string and accumulate the BigInteger's magnitude
                int digitIndex = 0; // index of digits array
                int substrEnd  = startChar + ((topChars == 0) ? charsPerInt : topChars);
                int newDigit;

                for (int substrStart = startChar;
                     substrStart < endChar;
                     substrStart = substrEnd, substrEnd = substrStart
                                                          + charsPerInt)
                {
                    int bigRadixDigit = Convert.ToInt32(s.Substring(substrStart, substrEnd - substrStart), radix);
                    newDigit             = Multiplication.MultiplyByInt(digits, digitIndex, bigRadix);
                    newDigit            += Elementary.inplaceAdd(digits, digitIndex, bigRadixDigit);
                    digits[digitIndex++] = newDigit;
                }

                numberLength = digitIndex;
            }
            catch (Exception ex)
            {
                exception = ex;
                value     = null;
                return(false);
            }

            value              = new BigInteger();
            value.sign         = sign;
            value.numberLength = numberLength;
            value.digits       = digits;
            value.CutOffLeadingZeroes();
            exception = null;
            return(true);
        }
コード例 #4
0
        /**
         * It uses the sieve of Eratosthenes to discard several composite numbers in
         * some appropriate range (at the moment {@code [this, this + 1024]}). After
         * this process it applies the Miller-Rabin test to the numbers that were
         * not discarded in the sieve.
         *
         * @see BigInteger#nextProbablePrime()
         * @see #millerRabin(BigInteger, int)
         */

        public static BigInteger NextProbablePrime(BigInteger n)
        {
            // PRE: n >= 0
            int i, j;
            int certainty;
            int gapSize = 1024;             // for searching of the next probable prime number

            int[]      modules     = new int[primes.Length];
            bool[]     isDivisible = new bool[gapSize];
            BigInteger startPoint;
            BigInteger probPrime;

            // If n < "last prime of table" searches next prime in the table
            if ((n.numberLength == 1) && (n.Digits[0] >= 0) &&
                (n.Digits[0] < primes[primes.Length - 1]))
            {
                for (i = 0; n.Digits[0] >= primes[i]; i++)
                {
                    ;
                }
                return(BIprimes[i]);
            }

            /*
             * Creates a "N" enough big to hold the next probable prime Note that: N <
             * "next prime" < 2*N
             */
            startPoint = new BigInteger(1, n.numberLength,
                                        new int[n.numberLength + 1]);
            Array.Copy(n.Digits, 0, startPoint.Digits, 0, n.numberLength);
            // To fix N to the "next odd number"
            if (BigInteger.TestBit(n, 0))
            {
                Elementary.inplaceAdd(startPoint, 2);
            }
            else
            {
                startPoint.Digits[0] |= 1;
            }
            // To set the improved certainly of Miller-Rabin
            j = startPoint.BitLength;
            for (certainty = 2; j < BITS[certainty]; certainty++)
            {
                ;
            }
            // To calculate modules: N mod p1, N mod p2, ... for first primes.
            for (i = 0; i < primes.Length; i++)
            {
                modules[i] = Division.Remainder(startPoint, primes[i]) - gapSize;
            }
            while (true)
            {
                // At this point, all numbers in the gap are initialized as
                // probably primes
                // Arrays.fill(isDivisible, false);
                for (int k = 0; k < isDivisible.Length; k++)
                {
                    isDivisible[k] = false;
                }

                // To discard multiples of first primes
                for (i = 0; i < primes.Length; i++)
                {
                    modules[i] = (modules[i] + gapSize) % primes[i];
                    j          = (modules[i] == 0) ? 0 : (primes[i] - modules[i]);
                    for (; j < gapSize; j += primes[i])
                    {
                        isDivisible[j] = true;
                    }
                }
                // To execute Miller-Rabin for non-divisible numbers by all first
                // primes
                for (j = 0; j < gapSize; j++)
                {
                    if (!isDivisible[j])
                    {
                        probPrime = startPoint.Copy();
                        Elementary.inplaceAdd(probPrime, j);

                        if (MillerRabin(probPrime, certainty))
                        {
                            return(probPrime);
                        }
                    }
                }
                Elementary.inplaceAdd(startPoint, gapSize);
            }
        }
コード例 #5
0
        /**
         *
         * Based on "New Algorithm for Classical Modular Inverse" Róbert Lórencz.
         * LNCS 2523 (2002)
         *
         * @return a^(-1) mod m
         */

        private static BigInteger ModInverseLorencz(BigInteger a, BigInteger modulo)
        {
            // PRE: a is coprime with modulo, a < modulo

            int max = System.Math.Max(a.numberLength, modulo.numberLength);

            int[] uDigits = new int[max + 1];             // enough place to make all the inplace operation
            int[] vDigits = new int[max + 1];
            Array.Copy(modulo.Digits, 0, uDigits, 0, modulo.numberLength);
            Array.Copy(a.Digits, 0, vDigits, 0, a.numberLength);
            BigInteger u = new BigInteger(modulo.Sign,
                                          modulo.numberLength,
                                          uDigits);
            BigInteger v = new BigInteger(a.Sign, a.numberLength, vDigits);

            BigInteger r = new BigInteger(0, 1, new int[max + 1]);             // BigInteger.ZERO;
            BigInteger s = new BigInteger(1, 1, new int[max + 1]);

            s.Digits[0] = 1;
            // r == 0 && s == 1, but with enough place

            int coefU = 0, coefV = 0;
            int n = modulo.BitLength;
            int k;

            while (!IsPowerOfTwo(u, coefU) && !IsPowerOfTwo(v, coefV))
            {
                // modification of original algorithm: I calculate how many times the algorithm will enter in the same branch of if
                k = HowManyIterations(u, n);

                if (k != 0)
                {
                    BitLevel.InplaceShiftLeft(u, k);
                    if (coefU >= coefV)
                    {
                        BitLevel.InplaceShiftLeft(r, k);
                    }
                    else
                    {
                        BitLevel.InplaceShiftRight(s, System.Math.Min(coefV - coefU, k));
                        if (k - (coefV - coefU) > 0)
                        {
                            BitLevel.InplaceShiftLeft(r, k - coefV + coefU);
                        }
                    }
                    coefU += k;
                }

                k = HowManyIterations(v, n);
                if (k != 0)
                {
                    BitLevel.InplaceShiftLeft(v, k);
                    if (coefV >= coefU)
                    {
                        BitLevel.InplaceShiftLeft(s, k);
                    }
                    else
                    {
                        BitLevel.InplaceShiftRight(r, System.Math.Min(coefU - coefV, k));
                        if (k - (coefU - coefV) > 0)
                        {
                            BitLevel.InplaceShiftLeft(s, k - coefU + coefV);
                        }
                    }
                    coefV += k;
                }

                if (u.Sign == v.Sign)
                {
                    if (coefU <= coefV)
                    {
                        Elementary.completeInPlaceSubtract(u, v);
                        Elementary.completeInPlaceSubtract(r, s);
                    }
                    else
                    {
                        Elementary.completeInPlaceSubtract(v, u);
                        Elementary.completeInPlaceSubtract(s, r);
                    }
                }
                else
                {
                    if (coefU <= coefV)
                    {
                        Elementary.completeInPlaceAdd(u, v);
                        Elementary.completeInPlaceAdd(r, s);
                    }
                    else
                    {
                        Elementary.completeInPlaceAdd(v, u);
                        Elementary.completeInPlaceAdd(s, r);
                    }
                }
                if (v.Sign == 0 || u.Sign == 0)
                {
                    // math.19: BigInteger not invertible
                    throw new ArithmeticException(Messages.math19);
                }
            }

            if (IsPowerOfTwo(v, coefV))
            {
                r = s;
                if (v.Sign != u.Sign)
                {
                    u = -u;
                }
            }
            if (BigInteger.TestBit(u, n))
            {
                if (r.Sign < 0)
                {
                    r = -r;
                }
                else
                {
                    r = modulo - r;
                }
            }
            if (r.Sign < 0)
            {
                r += modulo;
            }

            return(r);
        }
コード例 #6
0
        /**
         * Calculates a.modInverse(p) Based on: Savas, E; Koc, C "The Montgomery Modular
         * Inverse - Revised"
         */

        public static BigInteger ModInverseMontgomery(BigInteger a, BigInteger p)
        {
            if (a.Sign == 0)
            {
                // ZERO hasn't inverse
                // math.19: BigInteger not invertible
                throw new ArithmeticException(Messages.math19);
            }

            if (!BigInteger.TestBit(p, 0))
            {
                // montgomery inverse require even modulo
                return(ModInverseLorencz(a, p));
            }

            int m = p.numberLength * 32;
            // PRE: a \in [1, p - 1]
            BigInteger u, v, r, s;

            u = p.Copy();             // make copy to use inplace method
            v = a.Copy();
            int max = System.Math.Max(v.numberLength, u.numberLength);

            r           = new BigInteger(1, 1, new int[max + 1]);
            s           = new BigInteger(1, 1, new int[max + 1]);
            s.Digits[0] = 1;
            // s == 1 && v == 0

            int k = 0;

            int lsbu = u.LowestSetBit;
            int lsbv = v.LowestSetBit;
            int toShift;

            if (lsbu > lsbv)
            {
                BitLevel.InplaceShiftRight(u, lsbu);
                BitLevel.InplaceShiftRight(v, lsbv);
                BitLevel.InplaceShiftLeft(r, lsbv);
                k += lsbu - lsbv;
            }
            else
            {
                BitLevel.InplaceShiftRight(u, lsbu);
                BitLevel.InplaceShiftRight(v, lsbv);
                BitLevel.InplaceShiftLeft(s, lsbu);
                k += lsbv - lsbu;
            }

            r.Sign = 1;
            while (v.Sign > 0)
            {
                // INV v >= 0, u >= 0, v odd, u odd (except last iteration when v is even (0))

                while (u.CompareTo(v) > BigInteger.EQUALS)
                {
                    Elementary.inplaceSubtract(u, v);
                    toShift = u.LowestSetBit;
                    BitLevel.InplaceShiftRight(u, toShift);
                    Elementary.inplaceAdd(r, s);
                    BitLevel.InplaceShiftLeft(s, toShift);
                    k += toShift;
                }

                while (u.CompareTo(v) <= BigInteger.EQUALS)
                {
                    Elementary.inplaceSubtract(v, u);
                    if (v.Sign == 0)
                    {
                        break;
                    }
                    toShift = v.LowestSetBit;
                    BitLevel.InplaceShiftRight(v, toShift);
                    Elementary.inplaceAdd(s, r);
                    BitLevel.InplaceShiftLeft(r, toShift);
                    k += toShift;
                }
            }
            if (!u.IsOne)
            {
                // in u is stored the gcd
                // math.19: BigInteger not invertible.
                throw new ArithmeticException(Messages.math19);
            }
            if (r.CompareTo(p) >= BigInteger.EQUALS)
            {
                Elementary.inplaceSubtract(r, p);
            }

            r = p - r;

            // Have pair: ((BigInteger)r, (Integer)k) where r == a^(-1) * 2^k mod (module)
            int n1 = CalcN(p);

            if (k > m)
            {
                r = MonPro(r, BigInteger.One, p, n1);
                k = k - m;
            }

            r = MonPro(r, BigInteger.GetPowerOfTwo(m - k), p, n1);
            return(r);
        }
コード例 #7
0
        /**
         * @param m a positive modulus
         * Return the greatest common divisor of op1 and op2,
         *
         * @param op1
         *            must be greater than zero
         * @param op2
         *            must be greater than zero
         * @see BigInteger#gcd(BigInteger)
         * @return {@code GCD(op1, op2)}
         */

        public static BigInteger GcdBinary(BigInteger op1, BigInteger op2)
        {
            // PRE: (op1 > 0) and (op2 > 0)

            /*
             * Divide both number the maximal possible times by 2 without rounding
             * gcd(2*a, 2*b) = 2 * gcd(a,b)
             */
            int lsb1      = op1.LowestSetBit;
            int lsb2      = op2.LowestSetBit;
            int pow2Count = System.Math.Min(lsb1, lsb2);

            BitLevel.InplaceShiftRight(op1, lsb1);
            BitLevel.InplaceShiftRight(op2, lsb2);

            BigInteger swap;

            // I want op2 > op1
            if (op1.CompareTo(op2) == BigInteger.GREATER)
            {
                swap = op1;
                op1  = op2;
                op2  = swap;
            }

            do
            {
                // INV: op2 >= op1 && both are odd unless op1 = 0

                // Optimization for small operands
                // (op2.bitLength() < 64) implies by INV (op1.bitLength() < 64)
                if ((op2.numberLength == 1) ||
                    ((op2.numberLength == 2) && (op2.Digits[1] > 0)))
                {
                    op2 = BigInteger.FromInt64(Division.GcdBinary(op1.ToInt64(),
                                                                  op2.ToInt64()));
                    break;
                }

                // Implements one step of the Euclidean algorithm
                // To reduce one operand if it's much smaller than the other one
                if (op2.numberLength > op1.numberLength * 1.2)
                {
                    op2 = BigMath.Remainder(op2, op1);
                    if (op2.Sign != 0)
                    {
                        BitLevel.InplaceShiftRight(op2, op2.LowestSetBit);
                    }
                }
                else
                {
                    // Use Knuth's algorithm of successive subtract and shifting
                    do
                    {
                        Elementary.inplaceSubtract(op2, op1);                         // both are odd
                        BitLevel.InplaceShiftRight(op2, op2.LowestSetBit);            // op2 is even
                    } while (op2.CompareTo(op1) >= BigInteger.EQUALS);
                }
                // now op1 >= op2
                swap = op2;
                op2  = op1;
                op1  = swap;
            } while (op1.Sign != 0);
            return(op2 << pow2Count);
        }
コード例 #8
0
        /** @see BigInteger#subtract(BigInteger) */
        internal static BigInteger subtract(BigInteger op1, BigInteger op2)
        {
            int resSign;

            int[] resDigits;
            int   op1Sign = op1.Sign;
            int   op2Sign = op2.Sign;

            if (op2Sign == 0)
            {
                return(op1);
            }
            if (op1Sign == 0)
            {
                return(-op2);
            }
            int op1Len = op1.numberLength;
            int op2Len = op2.numberLength;

            if (op1Len + op2Len == 2)
            {
                long a = (op1.Digits[0] & 0xFFFFFFFFL);
                long b = (op2.Digits[0] & 0xFFFFFFFFL);
                if (op1Sign < 0)
                {
                    a = -a;
                }
                if (op2Sign < 0)
                {
                    b = -b;
                }
                return(BigInteger.FromInt64(a - b));
            }
            int cmp = ((op1Len != op2Len) ? ((op1Len > op2Len) ? 1 : -1)
                                        : Elementary.CompareArrays(op1.Digits, op2.Digits, op1Len));

            if (cmp == BigInteger.LESS)
            {
                resSign   = -op2Sign;
                resDigits = (op1Sign == op2Sign) ? subtract(op2.Digits, op2Len,
                                                            op1.Digits, op1Len) : add(op2.Digits, op2Len, op1.Digits,
                                                                                      op1Len);
            }
            else
            {
                resSign = op1Sign;
                if (op1Sign == op2Sign)
                {
                    if (cmp == BigInteger.EQUALS)
                    {
                        return(BigInteger.Zero);
                    }
                    resDigits = subtract(op1.Digits, op1Len, op2.Digits, op2Len);
                }
                else
                {
                    resDigits = add(op1.Digits, op1Len, op2.Digits, op2Len);
                }
            }
            BigInteger res = new BigInteger(resSign, resDigits.Length, resDigits);

            res.CutOffLeadingZeroes();
            return(res);
        }
コード例 #9
0
 /// <summary>
 /// Subtracts a big integer value from another
 /// </summary>
 /// <param name="a">The subtrahend value</param>
 /// <param name="b">The subtractor value</param>
 /// <returns>
 /// </returns>
 public static BigInteger Subtract(BigInteger a, BigInteger b)
 {
     return(Elementary.subtract(a, b));
 }
コード例 #10
0
 /// <summary>
 /// Computes an addition between two big integer numbers
 /// </summary>
 /// <param name="a">The first term of the addition</param>
 /// <param name="b">The second term of the addition</param>
 /// <returns>Returns a new <see cref="BigInteger"/> that
 /// is the result of the addition of the two integers specified</returns>
 public static BigInteger Add(BigInteger a, BigInteger b)
 {
     return(Elementary.Add(a, b));
 }