Source of BitSetTest.java


  1: // Fig. I.10: BitSetTest.java
  2: // Using a BitSet to demonstrate the Sieve of Eratosthenes.
  3: import java.util.BitSet;
  4: import java.util.Scanner;
  5: 
  6: public class BitSetTest 
  7: {
  8:    public static void main( String args[] )
  9:    {
 10:       // get input integer
 11:       Scanner scanner = new Scanner( System.in );
 12:       System.out.println( "Please enter an integer from 2 to 1023" );
 13:       int input = scanner.nextInt();
 14: 
 15:       // perform Sieve of Eratosthenes
 16:       BitSet sieve = new BitSet( 1024 );
 17:       int size = sieve.size(); 
 18: 
 19:       // set all bits from 2 to 1023
 20:       for ( int i = 2; i < size; i++ )
 21:          sieve.set( i );
 22: 
 23:       // perform Sieve of Eratosthenes
 24:       int finalBit = ( int ) Math.sqrt( size );
 25: 
 26:       for ( int i = 2; i < finalBit; i++ ) 
 27:       {
 28:          if ( sieve.get( i ) ) 
 29:          {
 30:             for ( int j = 2 * i; j < size; j += i ) 
 31:                sieve.clear( j );
 32:          } // end if
 33:       } // end for
 34: 
 35:       int counter = 0; 
 36: 
 37:       // display prime numbers from 2 to 1023
 38:       for ( int i = 2; i < size; i++ )
 39:       {
 40:          if ( sieve.get( i ) ) 
 41:          {
 42:             System.out.print( String.valueOf( i ) );
 43:             System.out.print( ++counter % 7 == 0 ? "\n" : "\t" );
 44:          } // end if
 45:       } // end for
 46: 
 47:       // display result
 48:       if ( sieve.get( input ) )
 49:          System.out.printf( "\n%d is a prime number", input );
 50:       else
 51:          System.out.printf( "\n%d is not a prime number", input );
 52:    } // end main
 53: } // end class BitSetTest
 54: 
 55: /**************************************************************************
 56:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 57:  * Pearson Education, Inc. All Rights Reserved.                           *
 58:  *                                                                        *
 59:  * DISCLAIMER: The authors and publisher of this book have used their     *
 60:  * best efforts in preparing the book. These efforts include the          *
 61:  * development, research, and testing of the theories and programs        *
 62:  * to determine their effectiveness. The authors and publisher make       *
 63:  * no warranty of any kind, expressed or implied, with regard to these    *
 64:  * programs or to the documentation contained in these books. The authors *
 65:  * and publisher shall not be liable in any event for incidental or       *
 66:  * consequential damages in connection with, or arising out of, the       *
 67:  * furnishing, performance, or use of these programs.                     *
 68:  *************************************************************************/