计算从2~200万的素数数量
Java使用位集(BitSet)计算从2~200万中素数的数量
思想:从2开始,清除其倍数(4,6,8 . . .)
1 package Chapter9; 2 3 import java.util.BitSet; 4 5 /** 6 * @author MrNiurh 7 * @date Creat in 2020/12/13 8 * @description This program runs the Sieve of Erathostenes benchmark.It computes all primes up to 2,000,000. 9 * @see <a href="https://github.com/MrNiurh?tab=repositories">github</a> 10 */ 11 public class Sieve { 12 13 // 9.7.5 位集 14 15 /** 16 * 遍历一个包含 200 万个位的位集。首先将所有的位置为“开”状态,然后,将已知素数的倍数所对应的位都置为“关”状态。 17 * 18 * @param args 19 * @return void 20 */ 21 public static void main(String[] args) { 22 23 int n = 2000000; 24 long start = System.currentTimeMillis(); 25 26 var bitSet = new BitSet(n + 1); 27 int count = 0; 28 int i; 29 for (i = 2; i <= n; i++) { 30 // 设置一个位 31 bitSet.set(i); 32 } 33 i = 2; 34 35 while (i * i <= n) { 36 if (bitSet.get(i)) { 37 count++; 38 // 清除 i 的倍数位 39 int k = 2 * i; 40 while (k <= n) { 41 // 清除一个位 42 bitSet.clear(k); 43 k += i; 44 } 45 } 46 i++; 47 } 48 49 i = 2; 50 while (i <= n) { 51 if (bitSet.get(i)) count++; 52 i++; 53 } 54 55 long end = System.currentTimeMillis(); 56 System.out.println(count + " primes"); 57 System.out.println((end - start) + " ms"); 58 } 59 }