Hardware divides one bit at a time. For each bit of the dividend, it shifts the remainder, tries to subtract the divisor, and undoes the subtraction if it was too much.
What to build
A program that divides two unsigned n-bit numbers with restoring division and reports how many restores were needed.
Requirements
- The dividend has n bits. Start with remainder 0 and quotient 0. For each dividend bit from the most significant down: shift the remainder left and bring in the bit, subtract the divisor, and if the result is negative add the divisor back (one restore) and shift 0 into the quotient, otherwise shift in 1.
- Print
quotient Q remainder R restores K.
Input
One line: the dividend, the divisor and n.
Output
One line.
Constraints
The divisor is at least 1; the dividend is below 2ⁿ; 1 ≤ n ≤ 30.
Example
Input:
13 3 4
Output:
quotient 4 remainder 1 restores 3
Why it works
Each step asks whether the divisor fits into the current partial remainder. If it does not, the trial subtraction went negative and must be undone, which is exactly why the method is called restoring.
Examples
13 3 4
quotient 4 remainder 1 restores 3
15 1 4
quotient 15 remainder 0 restores 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Go from bit n - 1 down to bit 0 of the dividend: remainder = (remainder << 1) | bit, then remainder -= divisor.
Hint 2
If the remainder is now negative, add the divisor back (a restore) and shift a 0 into the quotient; otherwise shift in a 1.
Hint 3
Count the number of restores.
Solution
Show one correct solution (try it yourself first)
dividend, divisor, n = map(int, input().split())
rem = quo = restores = 0
for i in range(n - 1, -1, -1):
rem = (rem << 1) | ((dividend >> i) & 1)
rem -= divisor
if rem < 0:
rem += divisor
restores += 1
quo = quo << 1
else:
quo = (quo << 1) | 1
print("quotient", quo, "remainder", rem, "restores", restores)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step