Last active
December 24, 2015 22:09
-
-
Save tyrcho/6870819 to your computer and use it in GitHub Desktop.
scala primes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.Await | |
import scala.concurrent.duration.DurationInt | |
object ParallelPrimesCompute extends App { | |
val primes: Stream[Long] = | |
2L #:: Stream.range(3, Long.MaxValue, 2).filter( | |
n => primes.takeWhile(_ <= Math.sqrt(n)).forall(n % _ != 0)) | |
def runAll(functions: Iterable[() => Long]): Future[Any] = { | |
val futures = functions.map(f => Future { f() }) | |
for { | |
collection <- Future.sequence(futures) | |
} yield collection.sum | |
} | |
val costlyCalls = (1 to 60 * 1000).map(i => sumNprimes(i) _) | |
val res = Await.result(runAll(costlyCalls), 50.seconds) | |
println(res) | |
def sumNprimes(n: Int)(): Long = { | |
val name = Thread.currentThread.getName | |
val res = primes.take(n).sum | |
println(s"$n $name => $res") | |
res | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val primes:Stream[Int] = | |
2 #:: Stream.from(3,2).filter( | |
n => !primes.takeWhile(_ <= Math.sqrt(n)).exists(n % _ ==0)) | |
primes take 100 foreach println |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment