1 /*
   2  * Copyright 1999-2007 Sun Microsystems, Inc.  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.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any 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      */
  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      */
  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 r = new MutableBigInteger();
 114         MutableBigInteger q = new MutableBigInteger();
 115         do {
 116             // Calculate base mod convertedStep
 117             r.copyValue(base.mag);
 118             r.divideOneWord(convertedStep, q);
 119             start = r.value[r.offset];
 120 
 121             // Take each multiple of step out of sieve
 122             start = convertedStep - start;
 123             if (start%2 == 0)
 124                 start += convertedStep;
 125             sieveSingle(searchLen, (start-1)/2, convertedStep);
 126 
 127             // Find next prime from small sieve
 128             step = smallSieve.sieveSearch(smallSieve.length, step+1);
 129             convertedStep = (step *2) + 1;
 130         } while (step > 0);
 131     }
 132 
 133     /**
 134      * Given a bit index return unit index containing it.
 135      */
 136     private static int unitIndex(int bitIndex) {
 137         return bitIndex >>> 6;
 138     }
 139 
 140     /**
 141      * Return a unit that masks the specified bit in its unit.
 142      */
 143     private static long bit(int bitIndex) {
 144         return 1L << (bitIndex & ((1<<6) - 1));
 145     }
 146 
 147     /**
 148      * Get the value of the bit at the specified index.
 149      */
 150     private boolean get(int bitIndex) {
 151         int unitIndex = unitIndex(bitIndex);
 152         return ((bits[unitIndex] & bit(bitIndex)) != 0);
 153     }
 154 
 155     /**
 156      * Set the bit at the specified index.
 157      */
 158     private void set(int bitIndex) {
 159         int unitIndex = unitIndex(bitIndex);
 160         bits[unitIndex] |= bit(bitIndex);
 161     }
 162 
 163     /**
 164      * This method returns the index of the first clear bit in the search
 165      * array that occurs at or after start. It will not search past the
 166      * specified limit. It returns -1 if there is no such clear bit.
 167      */
 168     private int sieveSearch(int limit, int start) {
 169         if (start >= limit)
 170             return -1;
 171 
 172         int index = start;
 173         do {
 174             if (!get(index))
 175                 return index;
 176             index++;
 177         } while(index < limit-1);
 178         return -1;
 179     }
 180 
 181     /**
 182      * Sieve a single set of multiples out of the sieve. Begin to remove
 183      * multiples of the specified step starting at the specified start index,
 184      * up to the specified limit.
 185      */
 186     private void sieveSingle(int limit, int start, int step) {
 187         while(start < limit) {
 188             set(start);
 189             start += step;
 190         }
 191     }
 192 
 193     /**
 194      * Test probable primes in the sieve and return successful candidates.
 195      */
 196     BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) {
 197         // Examine the sieve one long at a time to find possible primes
 198         int offset = 1;
 199         for (int i=0; i<bits.length; i++) {
 200             long nextLong = ~bits[i];
 201             for (int j=0; j<64; j++) {
 202                 if ((nextLong & 1) == 1) {
 203                     BigInteger candidate = initValue.add(
 204                                            BigInteger.valueOf(offset));
 205                     if (candidate.primeToCertainty(certainty, random))
 206                         return candidate;
 207                 }
 208                 nextLong >>>= 1;
 209                 offset+=2;
 210             }
 211         }
 212         return null;
 213     }
 214 }