java- use BitSet 查找 prime number

Sequences may be used for the efficient storage product bits, since the bits set in the byte position in the package, the bit set ArrayList than using Boolean object more efficiently.

 

Own code, prime number is false

public class Sieve {
    @Test
    public void testMethod(){
        int n = 200;
        long start = System.currentTimeMillis();
        BitSet b = new BitSet(n+1);

        System.out.println(b.size());
        for(int i =3;i<b.size();i++) {
            if (i % 2 == 0) {
                b.set(i);//置为true
            }
           int j =3;
           while(i*j<b.size()){
               System.out.println(i*j);
                    b.set(i*j);
                    j++;
                }
            }
        for(int i =0;i<b.size();i++){
            System.out.println(i+":"+b.get(i));
        }
    }
}

  

java-core code, prime number is true, about the same algorithm, but I have to i * j, he used k≤n, k + = i

public class Sieve {
    @Test
    public void testMethod(){
        int n = 200;
        long start = System.currentTimeMillis();
        BitSet b = new BitSet(n+1);
        int count = 0;
        int i ;
        for(i=2;i<=n;i++){
            b.set(i);
        }
        i=2;
        while(i*i<=n){
            if(b.get(i)){
//                count++;//???
                int k = 2*i;
                while(k<=n){
                    //false,不是素数
                    b.clear(k);
                    k+=i;//n=(2--根号n)*(2--n/i)
                }
            }
            i++;
        }
        while(i<=n){
            if(b.get(i)) count++;
            i++;
        }
        long end = System.currentTimeMillis();
        //读取次数 46次
        System.out.println(count+"primes");
                System.out.println((end-start)+"milliseconds");
    }
}

  

Guess you like

Origin www.cnblogs.com/zhizhiyin/p/11130624.html