Path: blob/master/src/java.base/share/classes/java/math/BitSieve.java
41152 views
/*1* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.math;2627/**28* A simple bit sieve used for finding prime number candidates. Allows setting29* and clearing of bits in a storage array. The size of the sieve is assumed to30* be constant to reduce overhead. All the bits of a new bitSieve are zero, and31* bits are removed from it by setting them.32*33* To reduce storage space and increase efficiency, no even numbers are34* represented in the sieve (each bit in the sieve represents an odd number).35* The relationship between the index of a bit and the number it represents is36* given by37* N = offset + (2*index + 1);38* Where N is the integer represented by a bit in the sieve, offset is some39* even integer offset indicating where the sieve begins, and index is the40* index of a bit in the sieve array.41*42* @see BigInteger43* @author Michael McCloskey44* @since 1.345*/46class BitSieve {47/**48* Stores the bits in this bitSieve.49*/50private long bits[];5152/**53* Length is how many bits this sieve holds.54*/55private int length;5657/**58* A small sieve used to filter out multiples of small primes in a search59* sieve.60*/61private static BitSieve smallSieve = new BitSieve();6263/**64* Construct a "small sieve" with a base of 0. This constructor is65* used internally to generate the set of "small primes" whose multiples66* are excluded from sieves generated by the main (package private)67* constructor, BitSieve(BigInteger base, int searchLen). The length68* of the sieve generated by this constructor was chosen for performance;69* it controls a tradeoff between how much time is spent constructing70* other sieves, and how much time is wasted testing composite candidates71* for primality. The length was chosen experimentally to yield good72* performance.73*/74private BitSieve() {75length = 150 * 64;76bits = new long[(unitIndex(length - 1) + 1)];7778// Mark 1 as composite79set(0);80int nextIndex = 1;81int nextPrime = 3;8283// Find primes and remove their multiples from sieve84do {85sieveSingle(length, nextIndex + nextPrime, nextPrime);86nextIndex = sieveSearch(length, nextIndex + 1);87nextPrime = 2*nextIndex + 1;88} while((nextIndex > 0) && (nextPrime < length));89}9091/**92* Construct a bit sieve of searchLen bits used for finding prime number93* candidates. The new sieve begins at the specified base, which must94* be even.95*/96BitSieve(BigInteger base, int searchLen) {97/*98* Candidates are indicated by clear bits in the sieve. As a candidates99* nonprimality is calculated, a bit is set in the sieve to eliminate100* it. To reduce storage space and increase efficiency, no even numbers101* are represented in the sieve (each bit in the sieve represents an102* odd number).103*/104bits = new long[(unitIndex(searchLen-1) + 1)];105length = searchLen;106int start = 0;107108int step = smallSieve.sieveSearch(smallSieve.length, start);109int convertedStep = (step *2) + 1;110111// Construct the large sieve at an even offset specified by base112MutableBigInteger b = new MutableBigInteger(base);113MutableBigInteger q = new MutableBigInteger();114do {115// Calculate base mod convertedStep116start = b.divideOneWord(convertedStep, q);117118// Take each multiple of step out of sieve119start = convertedStep - start;120if (start%2 == 0)121start += convertedStep;122sieveSingle(searchLen, (start-1)/2, convertedStep);123124// Find next prime from small sieve125step = smallSieve.sieveSearch(smallSieve.length, step+1);126convertedStep = (step *2) + 1;127} while (step > 0);128}129130/**131* Given a bit index return unit index containing it.132*/133private static int unitIndex(int bitIndex) {134return bitIndex >>> 6;135}136137/**138* Return a unit that masks the specified bit in its unit.139*/140private static long bit(int bitIndex) {141return 1L << (bitIndex & ((1<<6) - 1));142}143144/**145* Get the value of the bit at the specified index.146*/147private boolean get(int bitIndex) {148int unitIndex = unitIndex(bitIndex);149return ((bits[unitIndex] & bit(bitIndex)) != 0);150}151152/**153* Set the bit at the specified index.154*/155private void set(int bitIndex) {156int unitIndex = unitIndex(bitIndex);157bits[unitIndex] |= bit(bitIndex);158}159160/**161* This method returns the index of the first clear bit in the search162* array that occurs at or after start. It will not search past the163* specified limit. It returns -1 if there is no such clear bit.164*/165private int sieveSearch(int limit, int start) {166if (start >= limit)167return -1;168169int index = start;170do {171if (!get(index))172return index;173index++;174} while(index < limit-1);175return -1;176}177178/**179* Sieve a single set of multiples out of the sieve. Begin to remove180* multiples of the specified step starting at the specified start index,181* up to the specified limit.182*/183private void sieveSingle(int limit, int start, int step) {184while(start < limit) {185set(start);186start += step;187}188}189190/**191* Test probable primes in the sieve and return successful candidates.192*/193BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) {194// Examine the sieve one long at a time to find possible primes195int offset = 1;196for (int i=0; i<bits.length; i++) {197long nextLong = ~bits[i];198for (int j=0; j<64; j++) {199if ((nextLong & 1) == 1) {200BigInteger candidate = initValue.add(201BigInteger.valueOf(offset));202if (candidate.primeToCertainty(certainty, random))203return candidate;204}205nextLong >>>= 1;206offset+=2;207}208}209return null;210}211}212213214