-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCheckedPow.java
More file actions
34 lines (30 loc) · 891 Bytes
/
CheckedPow.java
File metadata and controls
34 lines (30 loc) · 891 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
package expression.exceptions;
import expression.*;
public class CheckedPow extends Pow {
public CheckedPow(CommonExpression left, CommonExpression right) {
super(left, right);
}
public int compute(int x, int y) {
if (y < 0 || x == 0 && y == 0) {
throw new InvalidArgumentException(toString());
}
if (y == 0) {
return 1;
}
if (y == 1) {
return x;
}
if (y % 2 == 0) {
return compute(CheckMul(x, x), y / 2);
} else {
return CheckMul(x, compute(x, y - 1));
}
}
private int CheckMul(int x, int y) {
if (((y != 0) && (x * y / y != x)) || (x == Integer.MIN_VALUE && y == -1)
|| (y == Integer.MIN_VALUE && x == -1)) {
throw new OverflowException(toString());
}
return x * y;
}
}