If we are talking about implementing isPrime, then you should do as rossum suggested, even if the separation cost is more than the equality test, and with denser values ββfor lower values ββof n it will be asymptotically much faster. Moreover, it is very fast when testing non-prime numbers that have a small divisor (most numbers have)
It could be different if you want to test the primitiveness of the elements of another ascending stream. You might consider something like merge sorting. You did not specify how you want to get your result, here as a stream of Booleans, but it is not too difficult to adapt to something else.
def belong[A: Ordering](xs: Stream[A], ys: Stream[A]): Stream[Boolean] = { if (xs.isEmpty) Stream.empty else if (ys.isEmpty) xs.map(_ => true) else Ordering[A].compare(xs.head, ys.head) match { case less if less < 0 => false #:: belong(xs.tail, ys) case equal if equal == 0 => true #:: belong(xs.tail, ys.tail) case greater if greater > 0 => belong(xs, ys.tail) } }
So you can do belong(yourStream, primeStream)
However, it is not obvious that this solution will be better than a separate primitiveness test for each number, in turn, stopping at the square root. Especially if your thread is growing fast compared to primes, so you just need to compute a lot of primes just to keep up. And even to a lesser extent, if there is no reason to suspect that the elements in your stream are usually simple or have only large divisors.
source share