Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

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