-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEfficientPower.java
More file actions
46 lines (40 loc) · 981 Bytes
/
Copy pathEfficientPower.java
File metadata and controls
46 lines (40 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class EfficientPower {
/*
* Aim is to find the power of a number
* in an efficient manner. Let us denote
* the exponent by n.
*
* Time complexity: O(log2(n))
* Space complexity: O(1)
*/
public static void main(String[] args) {
double base = 10;
int exponent = 3;
System.out.println(fastPower(base, exponent)); // 1000.0
}
// Method for efficiently calculating power
private static double fastPower(double base, int exponent) {
if (exponent == 0) {
return 1;
}
// If exponent is negative, take reciporcal of base
// and then change sign of exponent
if (exponent < 0) {
base = 1 / base;
exponent = -exponent;
}
double answer = 1;
// Update answer based on binary
// representation of exponent
while (exponent != 0) {
// If bit is 1, update answer
if (exponent % 2 == 1) {
answer = answer * base;
}
// Move to next bit
base = base * base;
exponent = exponent / 2;
}
return answer;
}
}