Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Java Util Package Code Examples

Using a BitSet to demonstrate the Sieve of Eratosthenes

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
Using a BitSet to demonstrate the Sieve of Eratosthenes import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class BitSetTest extends JFrame { public BitSetTest() { super( "BitSets" ); final BitSet sieve = new BitSet( 1024 ); Container c = getContentPane(); final JLabel status = new JLabel(); c.add( status, BorderLayout.SOUTH ); JPanel inputPanel = new JPanel(); inputPanel.add( new JLabel( "Enter a value from " + "1 to 1023" ) ); final JTextField input = new JTextField( 10 ); input.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { int val = Integer.parseInt( input.getText() ); if ( sieve.get( val ) ) status.setText( val + " is a prime number" ); else status.setText( val + " is not a prime number" ); } } ); inputPanel.add( input ); c.add(inputPanel, BorderLayout.NORTH ); JTextArea primes = new JTextArea(); ScrollPane p = new ScrollPane(); p.add( primes ); c.add( p, BorderLayout.CENTER ); // set all bits from 1 to 1023 int size = sieve.size(); for ( int i = 1; i < size; i++ ) sieve.set( i ); // perform Sieve of Eratosthenes int finalBit = ( int ) Math.sqrt( sieve.size() ); for ( int i = 2; i < finalBit; i++ ) if ( sieve.get( i ) ) for ( int j = 2 * i; j < size; j += i ) sieve.clear( j ); int counter = 0; for ( int i = 1; i < size; i++ ) if ( sieve.get( i ) ) { primes.append( String.valueOf( i ) ); primes.append( ++counter % 7 == 0 ? "\n" : "\t" ); } setSize( 300, 250 ); show(); } public static void main( String args[] ) { BitSetTest app = new BitSetTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } }