清除Java中位集中索引的所有倍数?
我有一个位集,我想关闭给定索引的所有倍数。 例如:给定一个清除Java中位集中索引的所有倍数?,java,iteration,primes,bitset,Java,Iteration,Primes,Bitset,我有一个位集,我想关闭给定索引的所有倍数。 例如:给定一个位集-->{1,2,3,5,7,9,11,13,15,17},我想迭代位集,并关闭每个位集的倍数。最后,我应该有{1,2,3,5,7,11,13,17},它们都是素数。到目前为止,我已经: public static void getPrimeNumbers(int n) { BitSet s = new BitSet(); // s.set(0); s.set(1); s.set(2); //cr
位集-->{1,2,3,5,7,9,11,13,15,17}
,我想迭代位集
,并关闭每个位集的倍数。最后,我应该有{1,2,3,5,7,11,13,17}
,它们都是素数。到目前为止,我已经:
public static void getPrimeNumbers(int n) {
BitSet s = new BitSet();
// s.set(0);
s.set(1);
s.set(2);
//create the set having all numbers till n
for (int i = 3; i <= n; i += 2) {
s.set(i);
}
//for element in Bitset ....
//need to clear multiple of bits in iteration
}
publicstaticvoidgetprimenumbers(intn){
位集s=新位集();
//s.set(0);
s、 一套(1);
s、 组(2);
//创建包含所有数字的集合,直到n
对于(int i=3;i将“Eratosthenes筛”算法的筛移植到您的结构(位集)
应该足够直截了当
下面是一个使用数组的Java实现。
只需将其移植到位集
您可以这样做:
//you start from 3 because 1 and 2 are prime already
int i = 3;
//you can do square check, since you would have turned off all bits before you reach n
while (i * i < n) {
if (s.get(i)) {
int k = 3 * i;
while (k <= n) {
s.clear(k);
k += i;
}
}
i++;
}
//从3开始,因为1和2已经是素数了
int i=3;
//您可以进行平方检查,因为在到达n之前您会关闭所有位
而(i*i while(k)您可以使用while循环或for循环,检查(s.get(i))
,然后执行s.clear()
。除了1
不是素数,其他所有数字都是1
的倍数。
for (int j = s.nextSetBit(3);j>=0;j=s.nextSetBit(j+1)){
int k =3 * j;
while (k <= n){
s.clear(k);
k+=j;
}
}