I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it's like this
(x << 3) - x;
Now I know about basic bit manipulation operations, but I can't get how do you multiply a number by any other odd number without using the * operator? Is there a general algorithm for this?
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times.
It is quite easy to do it if you do not want to use the * sign to multiply directly. The first approach you can follow is to add the input values to the multiple values and this will provide the product of the two numbers.
Think about how you multiply in decimal using pencil and paper:
12 x 26 ---- 72 24 ---- 312
What does multiplication look like in binary?
0111 x 0101 ------- 0111 0000 0111 ------- 100011
Notice anything? Unlike multiplication in decimal, where you need to memorize the "times table," when multiplying in binary, you are always multiplying one of the terms by either 0 or 1 before writing it down in the list addends. There's no times table needed. If the digit of the second term is 1, you add in the first term. If it's 0, you don't. Also note how the addends are progressively shifted over to the left.
If you're unsure of this, do a few binary multiplications on paper. When you're done, convert the result back to decimal and see if it's correct. After you've done a few, I think you'll get the idea how binary multiplication can be implemented using shifts and adds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With