123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 |
- #include <vector>
- #include <cstdint>
- class BitSieve {
- using uint64_t = std::uint64_t;
-
- std::vector<uint64_t> bits;
-
- int length;
-
- static BitSieve smallSieve = new BitSieve();
-
- BitSieve() {
- length = 150 * 64;
- bits = std::vector<uint64_t>((unitIndex(length - 1) + 1));
-
- set(0);
- int nextIndex = 1;
- int nextPrime = 3;
-
- do {
- sieveSingle(length, nextIndex + nextPrime, nextPrime);
- nextIndex = sieveSearch(length, nextIndex + 1);
- nextPrime = 2*nextIndex + 1;
- } while((nextIndex > 0) && (nextPrime < length));
- }
-
- BitSieve(BigInteger base, int searchLen) {
-
- bits = std::vector<uint64_t>((unitIndex(length - 1) + 1));
- length = searchLen;
- int start = 0;
- int step = smallSieve.sieveSearch(smallSieve.length, start);
- int convertedStep = (step *2) + 1;
-
- MutableBigInteger b(base);
- MutableBigInteger q;
- do {
-
- start = b.divideOneWord(convertedStep, q);
-
- start = convertedStep - start;
- if (start%2 == 0)
- start += convertedStep;
- sieveSingle(searchLen, (start-1)/2, convertedStep);
-
- step = smallSieve.sieveSearch(smallSieve.length, step+1);
- convertedStep = (step *2) + 1;
- } while (step > 0);
- }
-
- static int unitIndex(unsigned int bitIndex) {
- return bitIndex >> 6;
- }
-
- static long bit(unsigned int bitIndex) {
- return 1ULL << (bitIndex & ((1<<6) - 1));
- }
-
- bool get(unsigned int bitIndex) {
- unsigned int unitIndex = unitIndex(bitIndex);
- return ((bits[unitIndex] & bit(bitIndex)) != 0);
- }
-
- void set(unsigned int bitIndex) {
- unsigned int unitIndex = unitIndex(bitIndex);
- bits[unitIndex] |= bit(bitIndex);
- }
-
- int sieveSearch(unsigned int limit, unsigned int start) {
- if (start >= limit)
- return -1;
- int index = start;
- do {
- if (!get(index))
- return index;
- index++;
- } while(index < limit-1);
- return -1;
- }
-
- void sieveSingle(int limit, int start, int step) {
- while(start < limit) {
- set(start);
- start += step;
- }
- }
-
- BigInteger retrieve(const BigInteger& initValue, unsigned int certainty, java.util.Random random) {
-
- int offset = 1;
- for (int i=0; i<bits.length; i++) {
- uint64_t nextLong = ~bits[i];
- for (int j=0; j<64; j++) {
- if ((nextLong & 1) == 1) {
- BigInteger candidate = initValue.add(
- BigInteger.valueOf(offset));
- if (candidate.primeToCertainty(certainty, random))
- return candidate;
- }
- nextLong >>= 1;
- offset += 2;
- }
- }
- return BigInteger(0);
- }
- }
|