File tree Expand file tree Collapse file tree 1 file changed +10
-5
lines changed Expand file tree Collapse file tree 1 file changed +10
-5
lines changed Original file line number Diff line number Diff line change @@ -10,14 +10,19 @@ public static void main(String[] args) {
10
10
}
11
11
12
12
/**
13
- * Divide n by 2
14
- *
13
+ * Binary Search, divide n by 2
15
14
* Questions:
16
15
* 1. can x be zero?
17
16
* 2. can n be negative?
17
+ *
18
18
* When n is odd, multiply result by f
19
19
* f multiply by itself each time
20
- * Repeat until n <= 0
20
+ * Repeat until n == 0
21
+ * x^10 = x^2 * x^8
22
+ * x^9 = x * x^8
23
+ * x^8 = x^8
24
+ * x^7 = x * x^2 * x^4
25
+ * x^6 = x^2 * x^4
21
26
*/
22
27
public double pow (double x , int n ) {
23
28
if (n == 0 ) return 1 ;
@@ -26,9 +31,9 @@ public double pow(double x, int n) {
26
31
x = 1 / x ; // x can be zero?
27
32
}
28
33
double res = 1 ; // mind overflow
29
- for (double f = x ; n > 0 ; n = n >> 1 ) { // n/=2
34
+ for (double f = x ; n > 0 ; n = n >> 1 ) { // n >>= 1, n /=2
30
35
if (n % 2 == 1 ) res *= f ;
31
- f = f * f ;
36
+ f = f * f ; // f *= f
32
37
}
33
38
return res ;
34
39
}
You can’t perform that action at this time.
0 commit comments