Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Last active December 24, 2015 22:09
Show Gist options
  • Save tyrcho/6870819 to your computer and use it in GitHub Desktop.
Save tyrcho/6870819 to your computer and use it in GitHub Desktop.
scala primes
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
}
}
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