高效存储为序列可以使用位积,由于位集将位包装在字节里,所以位集要比使用Boolean对象的ArrayList更高效。
自己的代码,素数是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
if (i % 2 == 0) {
b.set(i);//置为true
}
int j =3;
while(i*j
System.out.println(i*j);
b.set(i*j);
j++;
}
}
for(int i =0;i
System.out.println(i+":"+b.get(i));
}
}
}
java-core的代码,素数是true,算法差不多,只不过我用得i*j,他用的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");
}
}