December 2015
Intermediate to advanced
298 pages
5h 30m
English
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)) ...
Read now
Unlock full access