Hi, I am stuck for some days trying to understand the algorithm behind the problem 4.6 (Java version).
Sorry if this sounds to be a basic question but unfortunately I didn’t understand the principle adopted.
I’m trying to understand the paragraph:
- “A better approach is to try and get more work done in each iteration. For example, we can compute the largest k such that 2^k * y <= x, subtract 2^k * y from x, and add 2^k to the quotient. For example, if x = (1011)2 and y = (10)2, then k = 2, since 2 * 2^2 <= 11 and 2 * 2^3 > 11. We subtract (1000)2 from (1011)2 to get (11)2, add 2^k = 2^2 = (100)2 to the quotient, and continue by updating x to (11)2”
I’m trying to replicate this logic step by step but I must be missing something …:
-
We’re trying to divide 11/2 so x=11 and y=2
-
The paragraph states that 2^k * y <= x, so I’m doing the following:
for k=0, 2^0 * 2 = 2 2 <= 11 (true)
for k=1, 2^1 * 2 = 4 4 <= 11 (true)
for k=2, 2^2 * 2 = 8 8 <= 11 (true) <-- The largest value of k is 2
for k=3, 2^3 * 2 = 16 16 <= 11 (false) -
"We subtract (1000)2 (decimal 8) from (1011)2 (decimal 11)"
8-11=-3 (11)2 <-- Probably the negative sign is being discarded, result = 3 -
"add 2^k = 2^2 = (100)2 to the quotient…"
I “think” the quotient is k and k=2, so I need to perform:
2^k + k => 2^2 + 2 => 4 + 2 = 6, for sure there is something wrong here because the value is 6 -
The last phrase is “and continue by updating x to (11)2” … unfortunately I have no idea of what I need to perform here
Appreciate any help
Marcos