Binary multiplication needs only shifts and adds. Multiply two whole numbers the way hardware does and show each partial product.
What to build
A program that multiplies a by b with shift-and-add and prints the partial products.
Requirements
- Go through the bits of b from the least significant one. For every bit that is 1, print
bit i: add Xwhere X is a shifted left by i. - Finally print
product P.
Input
One line: a and b.
Output
One line for each 1 bit of b, then the product line.
Constraints
0 ≤ a, b ≤ 10⁶.
Example
Input:
13 11
Output:
bit 0: add 13
bit 1: add 26
bit 3: add 104
product 143
Why it works
Bit i of the multiplier is worth 2ⁱ, so it contributes a × 2ⁱ, which is a shifted left by i places. The sum of these partial products is a × b.
Examples
13 11
bit 0: add 13 bit 1: add 26 bit 3: add 104 product 143
5 0
product 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For each bit i of b from i = 0 upward: if (b >> i) & 1 is 1, add a << i to the product.
Hint 2
Stop when the bits of b run out: use a while loop on b >> i, or loop over range(b.bit_length()).
Solution
Show one correct solution (try it yourself first)
a, b = map(int, input().split())
product = 0
for i in range(b.bit_length()):
if (b >> i) & 1:
print(f"bit {i}: add {a << i}")
product += a << i
print("product", product)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step