... Eratosthenes, using a BitSet.


 1   // Fig. K.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      public static void main(String[] args) {
 8         // get input integer
 9         Scanner scanner = new Scanner(System.in);
10         System.out.println("Please enter an integer from 2 to 1023");
11         int input = scanner.nextInt();
12
13         // perform Sieve of Eratosthenes 
14         BitSet sieve = new BitSet(1024); 
15         int size = sieve.size();         
16
17         // set all bits from 2 to 1023
18         for (int i = 2; i < size; i++) {
19            sieve.set(i);
20         } 
21
22         // perform Sieve of Eratosthenes
23         int finalBit = (int) Math.sqrt(size); 
24
25         for (int i = 2; i < finalBit; i++) { 
26            if (sieve.get(i) ...

Get Java How to Program, Early Objects, 11th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.