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
24 lines (20 loc) · 468 Bytes
/
Pow.java
File metadata and controls
24 lines (20 loc) · 468 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
/**
* BigInteger exercise.
*/
public class Pow {
/**
* Integer exponentiation.
*/
public static int pow(int x, int n) {
if (n == 0) return 1;
// find x to the n/2 recursively
int 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;
}
}
}