Skip to content

Commit 8ac95e9

Browse files
committed
4.6 Primitive Divide - Add final optimal solution
1 parent 65a313f commit 8ac95e9

1 file changed

Lines changed: 20 additions & 4 deletions

File tree

epi_judge_java/epi/PrimitiveDivide.java

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,37 @@ public static int divide(int x, int y) {
1313
}
1414
return divide(x - y, y) + 1; */
1515

16-
// Optimal 1 (from Textbook)
16+
// Optimal 1 (initial approach)
1717
// Find largest k: (2^k)y <= x. Set x = 2*2^k and q += 2^k. Repeat divide.
18-
if (x < y) {
18+
// Time Complexity: O(n^2), where n - num of quotient bits
19+
/* if (x < y) {
1920
return 0;
2021
}
2122
2223
int k = 0;
2324
while (y < (x >>> (k+1))) {
2425
k += 1;
2526
}
26-
return divide(x - (1 << k)*y, y) + (1 << k);
27+
return divide(x - (1 << k)*y, y) + (1 << k); */
28+
29+
// Optimal 2 (textbook sol) - Simplify k finding
30+
// Note: Assumes non-negative inputs
31+
int q = 0;
32+
int k = 0;
33+
while (y <= (x >>> (k+1)))
34+
k += 1;
35+
36+
while (x >= y){
37+
while (y > (x >>> k))
38+
k -= 1;
39+
x -= (1 << k) * y;
40+
q += 1 << k;
41+
}
42+
return q;
2743
}
2844

2945
public static void main(String[] args) {
30-
//System.out.println(divide(2097428739, 186));
46+
//System.out.println(divide(123, 3));
3147
System.exit(
3248
GenericTest
3349
.runFromAnnotations(args, "PrimitiveDivide.java",

0 commit comments

Comments
 (0)