power-futures.scala 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import scala.actors.Futures._;
  2. object FastPower {
  3. /**
  4. * Calculate a power of two fast.
  5. */
  6. def fastPow(x: Int, n: Int): Long = {
  7. var result = 1L;
  8. val b = n.toBinaryString.reverse;
  9. for(d <- 0 until b.length()) {
  10. if(b.charAt(d).equals('1')){
  11. result *= scala.math.pow(x,
  12. scala.math.pow(2, d)).toLong;
  13. }
  14. }
  15. return result;
  16. }
  17. /**
  18. * Calculate a power of two fast and use Futures.
  19. */
  20. def fastPowParallel(x: Int, n: Int): Long = {
  21. var result = 1L;
  22. val b = n.toBinaryString.reverse;
  23. val tasks = for (d <- 0 until b.length())
  24. yield future
  25. {
  26. var interim = 0L;
  27. if (b.charAt(d).equals('1')){
  28. interim = scala.math.pow(x,
  29. scala.math.pow(2, d)).toLong;
  30. }
  31. interim;
  32. }
  33. val futureRes = awaitAll(20000L, tasks: _*);
  34. futureRes.foreach { res =>
  35. res match {
  36. case Some(x: Long) => if (x > 0)
  37. result *= x
  38. case None => throw new
  39. Exception("error")
  40. };
  41. }
  42. return result;
  43. }
  44. def main(args: Array[String]) {
  45. println(fastPowParallel(2, 9));
  46. // => 512
  47. }
  48. }