forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPow.java
More file actions
36 lines (31 loc) · 854 Bytes
/
Copy pathPow.java
File metadata and controls
36 lines (31 loc) · 854 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
/**
* BigInteger exercise.
*/
import java.math.BigInteger;
public class Pow {
public static void main(String[] args) {
System.out.println(pow(27, 13));
}
/**
* Integer exponentiation.
*/
public static BigInteger pow(int x, int n) {
BigInteger one = BigInteger.valueOf(1);
if (n == 0) return one;
// find x to the n/2 recursively
BigInteger bigX = BigInteger.valueOf(x);
BigInteger t = pow(x, n / 2);
// if n is even, the result is t squared
// if n is odd, the result is t squared times x
// if (n % 2 == 0) {
// return t * t;
// } else {
// return t * t * x;
// }
if (n % 2 == 0) {
return t.multiply(t);
} else {
return t.multiply(t.multiply(bigX));
}
}
}