Eratosthenes Sieve的实现在内部是如何工作的?

wsxa1bj1  于 2022-10-22  发布在  Java
关注(0)|答案(1)|浏览(148)

我找到了这个代码,它将N个前素数放入数组。

private IntPredicate p = x -> true;

private int[] primes(int n) {

    return IntStream.iterate(2, i -> i + 1)
        .filter(x -> p.test(x))
        .peek(i -> p = p.and(k -> k % i != 0))
        .limit(n)
        .toArray();
}

IntPredicate内部发生了什么?

4nkexdtk

4nkexdtk1#

此代码通过IntPredicate.and()方法生成聚合 predicate ,其工作方式如下:

p = x -> true; // for first stream element `2` - 
               //   which passes the predicate p

// Predicate p is being reassigned while
// peek() sees the element `2`, to
p = x -> true && x % 2 != 0

// The next stream element `3` passes the updated predicate
// And the predicate is being reassigned again while
// peek() sees the element `3` to

p = x -> true && x % 2 != 0 && x % 3 != 0

// And so on...

因此,成功传递filter的每个元素都会通过“逻辑与”&&将新条件附加到当前 predicate 。
在流执行结束时, predicate 将由条件组成,这些条件将根据结果中出现的所有素数检查给定的数。

注意此黑客实现已被破坏:

peek()是专门为支持调试而引入的操作。它并不意味着用于执行可能影响执行结果的操作。peek不能保证在并行执行时调用它的顺序,在某些情况下可以进行优化。

相关问题