void bigSieve (const BigInteger& base, const int numBits, BigInteger& result, const BigInteger& smallSieve, const int smallSieveSize) { jassert (! base[0]); // must be even! result.setBit (numBits); result.clearBit (numBits); // to enlarge the array int index = smallSieve.findNextClearBit (0); do { const int prime = (index << 1) + 1; BigInteger r (base), remainder; r.divideBy (prime, remainder); int i = prime - remainder.getBitRangeAsInt (0, 32); if (r.isZero()) i += prime; if ((i & 1) == 0) i += prime; i = (i - 1) >> 1; while (i < numBits) { result.setBit (i); i += prime; } index = smallSieve.findNextClearBit (index + 1); } while (index < smallSieveSize); }
bool passesMillerRabin (const BigInteger& n, int iterations) { const BigInteger one (1), two (2); const BigInteger nMinusOne (n - one); BigInteger d (nMinusOne); const int s = d.findNextSetBit (0); d >>= s; BigInteger smallPrimes; int numBitsInSmallPrimes = 0; for (;;) { numBitsInSmallPrimes += 256; createSmallSieve (numBitsInSmallPrimes, smallPrimes); const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits(); if (numPrimesFound > iterations + 1) break; } int smallPrime = 2; while (--iterations >= 0) { smallPrime = smallPrimes.findNextClearBit (smallPrime + 1); BigInteger r (smallPrime); r.exponentModulo (d, n); if (r != one && r != nMinusOne) { for (int j = 0; j < s; ++j) { r.exponentModulo (two, n); if (r == nMinusOne) break; } if (r != nMinusOne) return false; } } return true; }