File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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" ,
You can’t perform that action at this time.
0 commit comments