我最近在研究這組程式
算出2147000000質數有多少個只需要花10幾秒.....
不過幾乎看不懂.....
您認為這組程式寫得好嗎??
- public class PrimeFinder {
- private static class BitSet {
- private int bits[];
- public BitSet(int n) {
- this.bits = new int[(n + 31) / 32];
- }
- public final boolean get(int index) {
- return (bits[index >> 5] & (1 << (index & 0x1F))) != 0;
- }
- public final void set(int index) {
- bits[index >> 5] |= (1 << (index & 0x1F));
- }
- public final int bitsCount() {
- int count = 0;
- for (int x : bits) {
- for (; x != 0; x ^= (x & -x)) {
- ++count;
- }
- }
- return count;
- }
- }
- public int[] getPrimes(int range) {
- BitSet bitset = new BitSet(range + 1);
- int bound = (int) Math.sqrt(range);
- for (int i = 2; i <= bound; ++i) {
- if (bitset.get(i)) {
- continue;
- }
- for (int j = i * i; j <= range; j += i) {
- bitset.set(j);
- }
- }
- int count = range - 1 - bitset.bitsCount();
- int res[] = new int[count];
- for (int i = range; i > 1; --i) {
- if (!bitset.get(i)) {
- res[ --count] = i;
- }
- }
- return res;
- }
- public int getPrimesCount(int range) {
- int primes[] = getPrimes((int) Math.sqrt(range));
- int start = 2, step = 262144, count = 0;
- while (start <= range) {
- int end = Math.min(range + 1, start + step);
- count += sift(primes, start, end);
- start = end;
- }
- return count;
- }
- private int sift(int primes[], int start, int end) {
- BitSet bitset = new BitSet(end - start);
- int e = end - start;
- for (int p : primes) {
- int s = (Math.max(p * p, start) + p - 1) / p * p - start;
- for (int j = s; j < e; j += p) {
- bitset.set(j);
- }
- }
- return end - start - bitset.bitsCount();
- }
- public static void main(String argv[]) {
- int n = 2147000000;
- PrimeFinder engine = new PrimeFinder();
- long start = System.currentTimeMillis();
- System.out.println(engine.getPrimesCount(n));
- System.out.println(System.currentTimeMillis() - start);
- }
- }
複製代碼 |