Guest User

Untitled

a guest
Oct 26th, 2011
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.98 KB | None | 0 0
  1. package parfact
  2.  
  3. import java.util.concurrent._
  4.  
  5. object Factorial{
  6.   val CORES = 8;
  7.   val executor = Executors.newCachedThreadPool()
  8.   def done = executor.shutdown
  9.   def future(x: =>BigInt) = executor.submit(new Callable[BigInt]{def call = x})
  10.   def starts(i: Int, offset:Int) = Stream.range(1, i, i/CORES).map(_+offset)
  11.   def partialFactorial(start:Int, end:Int) = Stream.range(start, end+1).map(x=>BigInt(x)).foldLeft(BigInt(1))((x,y)=>x * y);
  12.   def pairsList(i: Int) = starts(i,0).zip(starts(i,-1).tail).toList
  13.   def pairsListWithLast(i: Int) = pairsList(i)++List((pairsList(i).last._2+1,i))
  14.   def partialFactorials(i: Int) = pairsListWithLast(i).map(x=>future({partialFactorial(x._1,x._2)})).map(_.get)
  15.   def apply(i: Int) = partialFactorials(i).foldLeft(BigInt(1))((x,y)=>x * y)
  16. }
  17. object Main {
  18.  
  19.   def main(args: Array[String]): Unit = {
  20.     val m = System.currentTimeMillis
  21.     val x = Factorial(1000000)
  22.     println((System.currentTimeMillis-m)/1000.0)
  23.     Factorial.done
  24.   }
  25. }
  26.  
Advertisement
Add Comment
Please, Sign In to add comment