1 /*
2  * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.math;
27 
28 /**
29  * A simple bit sieve used for finding prime number candidates. Allows setting
30  * and clearing of bits in a storage array. The size of the sieve is assumed to
31  * be constant to reduce overhead. All the bits of a new bitSieve are zero, and
32  * bits are removed from it by setting them.
33  *
34  * To reduce storage space and increase efficiency, no even numbers are
35  * represented in the sieve (each bit in the sieve represents an odd number).
36  * The relationship between the index of a bit and the number it represents is
37  * given by
38  * N = offset + (2*index + 1);
39  * Where N is the integer represented by a bit in the sieve, offset is some
40  * even integer offset indicating where the sieve begins, and index is the
41  * index of a bit in the sieve array.
42  *
43  * @see     BigInteger
44  * @author  Michael McCloskey
45  * @since   1.3
46  */
47 class BitSieve {
48     /**
49      * Stores the bits in this bitSieve.
50      */
51     private long bits[];
52 
53     /**
54      * Length is how many bits this sieve holds.
55      */
56     private int length;
57 
58     /**
59      * A small sieve used to filter out multiples of small primes in a search
60      * sieve.
61      */
62     private static BitSieve smallSieve = new BitSieve();
63 
64     /**
65      * Construct a "small sieve" with a base of 0.  This constructor is
66      * used internally to generate the set of "small primes" whose multiples
67      * are excluded from sieves generated by the main (package private)
68      * constructor, BitSieve(BigInteger base, int searchLen).  The length
69      * of the sieve generated by this constructor was chosen for performance;
70      * it controls a tradeoff between how much time is spent constructing
71      * other sieves, and how much time is wasted testing composite candidates
72      * for primality.  The length was chosen experimentally to yield good
73      * performance.
74      */
BitSieve()75     private BitSieve() {
76         length = 150 * 64;
77         bits = new long[(unitIndex(length - 1) + 1)];
78 
79         // Mark 1 as composite
80         set(0);
81         int nextIndex = 1;
82         int nextPrime = 3;
83 
84         // Find primes and remove their multiples from sieve
85         do {
86             sieveSingle(length, nextIndex + nextPrime, nextPrime);
87             nextIndex = sieveSearch(length, nextIndex + 1);
88             nextPrime = 2*nextIndex + 1;
89         } while((nextIndex > 0) && (nextPrime < length));
90     }
91 
92     /**
93      * Construct a bit sieve of searchLen bits used for finding prime number
94      * candidates. The new sieve begins at the specified base, which must
95      * be even.
96      */
BitSieve(BigInteger base, int searchLen)97     BitSieve(BigInteger base, int searchLen) {
98         /*
99          * Candidates are indicated by clear bits in the sieve. As a candidates
100          * nonprimality is calculated, a bit is set in the sieve to eliminate
101          * it. To reduce storage space and increase efficiency, no even numbers
102          * are represented in the sieve (each bit in the sieve represents an
103          * odd number).
104          */
105         bits = new long[(unitIndex(searchLen-1) + 1)];
106         length = searchLen;
107         int start = 0;
108 
109         int step = smallSieve.sieveSearch(smallSieve.length, start);
110         int convertedStep = (step *2) + 1;
111 
112         // Construct the large sieve at an even offset specified by base
113         MutableBigInteger b = new MutableBigInteger(base);
114         MutableBigInteger q = new MutableBigInteger();
115         do {
116             // Calculate base mod convertedStep
117             start = b.divideOneWord(convertedStep, q);
118 
119             // Take each multiple of step out of sieve
120             start = convertedStep - start;
121             if (start%2 == 0)
122                 start += convertedStep;
123             sieveSingle(searchLen, (start-1)/2, convertedStep);
124 
125             // Find next prime from small sieve
126             step = smallSieve.sieveSearch(smallSieve.length, step+1);
127             convertedStep = (step *2) + 1;
128         } while (step > 0);
129     }
130 
131     /**
132      * Given a bit index return unit index containing it.
133      */
unitIndex(int bitIndex)134     private static int unitIndex(int bitIndex) {
135         return bitIndex >>> 6;
136     }
137 
138     /**
139      * Return a unit that masks the specified bit in its unit.
140      */
bit(int bitIndex)141     private static long bit(int bitIndex) {
142         return 1L << (bitIndex & ((1<<6) - 1));
143     }
144 
145     /**
146      * Get the value of the bit at the specified index.
147      */
get(int bitIndex)148     private boolean get(int bitIndex) {
149         int unitIndex = unitIndex(bitIndex);
150         return ((bits[unitIndex] & bit(bitIndex)) != 0);
151     }
152 
153     /**
154      * Set the bit at the specified index.
155      */
set(int bitIndex)156     private void set(int bitIndex) {
157         int unitIndex = unitIndex(bitIndex);
158         bits[unitIndex] |= bit(bitIndex);
159     }
160 
161     /**
162      * This method returns the index of the first clear bit in the search
163      * array that occurs at or after start. It will not search past the
164      * specified limit. It returns -1 if there is no such clear bit.
165      */
sieveSearch(int limit, int start)166     private int sieveSearch(int limit, int start) {
167         if (start >= limit)
168             return -1;
169 
170         int index = start;
171         do {
172             if (!get(index))
173                 return index;
174             index++;
175         } while(index < limit-1);
176         return -1;
177     }
178 
179     /**
180      * Sieve a single set of multiples out of the sieve. Begin to remove
181      * multiples of the specified step starting at the specified start index,
182      * up to the specified limit.
183      */
sieveSingle(int limit, int start, int step)184     private void sieveSingle(int limit, int start, int step) {
185         while(start < limit) {
186             set(start);
187             start += step;
188         }
189     }
190 
191     /**
192      * Test probable primes in the sieve and return successful candidates.
193      */
retrieve(BigInteger initValue, int certainty, java.util.Random random)194     BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) {
195         // Examine the sieve one long at a time to find possible primes
196         int offset = 1;
197         for (int i=0; i<bits.length; i++) {
198             long nextLong = ~bits[i];
199             for (int j=0; j<64; j++) {
200                 if ((nextLong & 1) == 1) {
201                     BigInteger candidate = initValue.add(
202                                            BigInteger.valueOf(offset));
203                     if (candidate.primeToCertainty(certainty, random))
204                         return candidate;
205                 }
206                 nextLong >>>= 1;
207                 offset+=2;
208             }
209         }
210         return null;
211     }
212 }
213