Sieve of Eratosthenes

Star gazing at night—we sometimes wonder—How many stars are there in the universe? How many galaxies? How many natural numbers are there? All these are really not finite. They are infinite! Prime numbers are also infinite. A brilliant algorithm to find prime numbers was found by Eratosthenes of Cyrene, a Greek mathematician. Named after him, the Sieve of Eratosthenes algorithm can be very nicely expressed as follows:

scala> def numStream(n: Int): Stream[Int] = 
     | 
Stream.from(n)// 1
numStream: (n: Int)Stream[Int] 
scala> def sieve(stream: Stream[Int]): Stream[Int] = 
     |   stream.head #:: sieve((stream.tail) filter (x => x % stream.head != 0)) // 2
sieve: (stream: Stream[Int])Stream[Int] 
scala> val p = sieve(numStream(2)) ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.