[Math] Multiplying two numbers using only the “left shift” operator

computer sciencenumber theory

At Geeks for Geeks, I came across a question "Add two numbers without using arithmetic operators", which basically states that you can multiply two numbers using the left shift operator. I am confused how that can be accomplished. I am trying to understand the logic here. It states that

We can solve this problem with the shift operator. The idea is based
on the fact that every number can be represented in binary form. And
multiplication with a number is equivalent to multiplication with
powers of 2. Powers of 2 can be obtained using left shift operator.

I dont understand what the above means. I know that left shifting by 1 is like multiplying by 2, and left shifting by 2 is is like multiplying that number by 4. However, I am confused at how I can use left shift to evaluate something like 7 * 3 ?

Best Answer

I looked at the link, but couldn't find where it says the text you have quoted. Regardless, with what it says & for what you're asking for, i.e., multiplying by using just the shift operator, I believe it means that it works only for multiplying each power of $2$ by left shifting by that power value. You can then use the procedures & code in the link to add the numbers without using arithmetic operators, but with this also using bitwise XOR and AND.

With your example, note that $7 = 2^2 + 2^1 + 2^0$ and $3 = 2^1 + 2^0$. Let's say we start with $7$. Note that $7 \times 3$ is $7 \times \left(2^1 + 2^0\right)$. We use the distribution property to get that $7 \times 3 = 7 \times 2^1 + 7 \times 2^0$. For the first term, we can do a left-shift by $1$ bit, the add this to the original value as the second term is already $7$. As such, we get the result to be $\left(2^3 + 2^2 + 2^1\right) + \left(2^2 + 2^1 + 2^0\right)$, with this in decimal being $14 + 7 = 21$.

Alternatively, if we started with $3 = 2^1 + 2^0$, we would use that $7 = 2^2 + 2^1 + 2^0$ to do the multiplications & addition to get that $7 \times 3 = \left(2^3 + 2^2\right) + \left(2^2 + 2^1\right) + \left(2^1 + 2^0\right) = 21$. In this case, the terms are different, and there are $3$ instead of $2$, but the sum is still the same of course.