26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1192 <strong>Java</strong> Utilities Package and Bit Manipulation Chapter 20<br />

33<br />

34 // textfield for user <strong>to</strong> input a value from 2 <strong>to</strong> 1023<br />

35 inputField = new JTextField( 10 );<br />

36<br />

37 inputField.addActionListener(<br />

38<br />

39 new ActionListener() {<br />

40<br />

41 // determine whether value is prime number<br />

42 public void actionPerformed( ActionEvent event )<br />

43 {<br />

44 int value = Integer.parseInt( inputField.getText() );<br />

45<br />

46 if ( sieve.get( value ) )<br />

47 statusLabel.setText(<br />

48 value + " is a prime number" );<br />

49<br />

50 else<br />

51 statusLabel.setText( value +<br />

52 " is not a prime number" );<br />

53 }<br />

54 }<br />

55 );<br />

56<br />

57 inputPanel.add( inputField );<br />

58 container.add( inputPanel, BorderLayout.NORTH );<br />

59<br />

60 JTextArea primesArea = new JTextArea();<br />

61<br />

62 container.add( new JScrollPane( primesArea ),<br />

63 BorderLayout.CENTER );<br />

64<br />

65 // set all bits from 1 <strong>to</strong> 1023<br />

66 int size = sieve.size();<br />

67<br />

68 for ( int i = 2; i < size; i++ )<br />

69 sieve.set( i );<br />

70<br />

71 // perform Sieve of Era<strong>to</strong>sthenes<br />

72 int finalBit = ( int ) Math.sqrt( sieve.size() );<br />

73<br />

74 for ( int i = 2; i < finalBit; i++ )<br />

75<br />

76 if ( sieve.get( i ) )<br />

77<br />

78 for ( int j = 2 * i; j < size; j += i )<br />

79 sieve.clear( j );<br />

80<br />

81 // display prime numbers from 1 <strong>to</strong> 1023<br />

82 int counter = 0;<br />

83<br />

Fig. Fig. 20.13 20.13 20.13 Demonstrating the Sieve of Era<strong>to</strong>sthenes using a BitSet (part 2 of 3).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!