Exemplo n.º 1
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)
         */
        internal 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]);
            java.lang.SystemJ.arraycopy(n.digits, 0, startPoint.digits, 0, n.numberLength);
            // To fix N to the "next odd number"
            if (n.testBit(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
                java.util.Arrays <Object> .fill(isDivisible, 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);
            }
        }
Exemplo n.º 2
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)}
         */
        internal 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.getLowestSetBit();
            int lsb2      = op2.getLowestSetBit();
            int pow2Count = java.lang.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.valueOf(Division.gcdBinary(op1.longValue(),
                                                                op2.longValue()));
                    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 = op2.remainder(op1);
                    if (op2.signum() != 0)
                    {
                        BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit());
                    }
                }
                else
                {
                    // Use Knuth's algorithm of successive subtract and shifting
                    do
                    {
                        Elementary.inplaceSubtract(op2, op1);                   // both are odd
                        BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit()); // op2 is even
                    } while (op2.compareTo(op1) >= BigInteger.EQUALS);
                }
                // now op1 >= op2
                swap = op2;
                op2  = op1;
                op1  = swap;
            } while (op1.sign != 0);
            return(op2.shiftLeft(pow2Count));
        }
Exemplo n.º 3
0
        /*
         * Calculates a.modInverse(p) Based on: Savas, E; Koc, C "The Montgomery Modular
         * Inverse - Revised"
         */
        internal static BigInteger modInverseMontgomery(BigInteger a, BigInteger p)
        {
            if (a.sign == 0)
            {
                // ZERO hasn't inverse
                // math.19: BigInteger not invertible
                throw new ArithmeticException("BigInteger not invertible");
            }


            if (!p.testBit(0))
            {
                // montgomery inverse require even modulo
                return(modInverseHars(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 = java.lang.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.getLowestSetBit();
            int lsbv = v.getLowestSetBit();
            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.signum() > 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.getLowestSetBit();
                    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.signum() == 0)
                    {
                        break;
                    }
                    toShift = v.getLowestSetBit();
                    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("BigInteger not invertible");
            }
            if (r.compareTo(p) >= BigInteger.EQUALS)
            {
                Elementary.inplaceSubtract(r, p);
            }

            r = p.subtract(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);
        }
Exemplo n.º 4
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.negate());
            }
            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.valueOf(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);
        }