Есть интересная статья: http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
Я пытался перевести код Haskell, приведенный в этой статье, в Scala, но я не тестировал производительность.
object primes {
type SI = Stream[Int]
def sieve:SI = {
def wheel2357:SI = Stream(4,2,4,6,2,6,4,2,4,6,6,
2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,
6,4,2,4,6,2,6,4,2,4,2,10,2,10,2) append wheel2357
def spin(s:SI, n:Int):SI = Stream.cons(n, spin(s.tail, n + s.head))
case class It(value:Int, step:Int) {
def next = new It(value + step, step)
def atLeast(c:Int):It =
if (value >= c) this
else new It(value + step, step).atLeast(c)
}
implicit object ItOrdering extends Ordering[It] {
def compare(thiz:It, that:It) = {
val r = thiz.value - that.value
if (r == 0) thiz.step - that.step else r
}
}
import scala.collection.immutable.TreeSet
def sieve(cand:SI, set:Set[It]):SI = {
val c = cand.head
val set1 = TreeSet[It]() ++ set.dropWhile(_.value < c) ++
set.takeWhile(_.value < c).map(_.atLeast(c))
if (set1.elements.next.value == c) {
val set2 = TreeSet[It]() ++ set1.dropWhile(_.value == c) ++
set1.takeWhile(_.value == c).map(_.next)
sieve(cand.tail, set2)
} else {
Stream.cons(c, sieve(cand.tail, set1 + It(c*c,2*c)))
}
}
Stream(2,3,5,7,11) append sieve(spin(wheel2357,13),
new TreeSet[It] + It(121,22))
}
def main(args:Array[String]) {
sieve.takeWhile(_ < 1000).foreach(println)
}
}