O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required