Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package parfact
- import java.util.concurrent._
- object Factorial{
- val CORES = 8;
- val executor = Executors.newCachedThreadPool()
- def done = executor.shutdown
- def future(x: =>BigInt) = executor.submit(new Callable[BigInt]{def call = x})
- def starts(i: Int, offset:Int) = Stream.range(1, i, i/CORES).map(_+offset)
- def partialFactorial(start:Int, end:Int) = Stream.range(start, end+1).map(x=>BigInt(x)).foldLeft(BigInt(1))((x,y)=>x * y);
- def pairsList(i: Int) = starts(i,0).zip(starts(i,-1).tail).toList
- def pairsListWithLast(i: Int) = pairsList(i)++List((pairsList(i).last._2+1,i))
- def partialFactorials(i: Int) = pairsListWithLast(i).map(x=>future({partialFactorial(x._1,x._2)})).map(_.get)
- def apply(i: Int) = partialFactorials(i).foldLeft(BigInt(1))((x,y)=>x * y)
- }
- object Main {
- def main(args: Array[String]): Unit = {
- val m = System.currentTimeMillis
- val x = Factorial(1000000)
- println((System.currentTimeMillis-m)/1000.0)
- Factorial.done
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment