Given two integers, write a function to multiply them without using multiplication operator.
There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn’t become 1. In the process, whenever the second number become odd, we add the first number to result (result is initialized as 0)
The following is simple algorithm.
Let the two given numbers be 'a' and 'b' 1) Initialize result 'res' as 0. 2) Do following while 'b' is greater than 0 a) If 'b' is odd, add 'a' to 'res' b) Double 'a' and halve 'b' 3) Return 'res'.
How does this work?
The value of a*b is same as (a*2)*(b/2) if b is even, otherwise the value is same as ((a*2)*(b/2) + a). In the while loop, we keep multiplying ‘a’ with 2 and keep dividing ‘b’ by 2. If ‘b’ becomes odd in loop, we add ‘a’ to ‘res’. When value of ‘b’ becomes 1, the value of ‘res’ + ‘a’, gives us the result.
Note that when ‘b’ is a power of 2, the ‘res’ would remain 0 and ‘a’ would have the multiplication. See the reference for more information.
This article is compiled by Shalki Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Multiply two integers without using multiplication, division and bitwise operators, and no loops
- Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
- Multiply a number by 15 without using * and / operators
- Multiply any Number with 4 using Bitwise Operator
- Minimum possible Bitwise OR of all Bitwise AND of pairs generated from two given arrays
- Check if a number is multiple of 9 using bitwise operators
- Case conversion (Lower to Upper and Vice Versa) of a string using BitWise operators in C/C++
- Toggle case of a string using Bitwise Operators
- Check if a number is divisible by 17 using bitwise operators
- Check if a number is divisible by 8 using bitwise operators
- Check if a Number is Odd or Even using Bitwise Operators
- Generate first K multiples of N using Bitwise operators
- Operators in C | Set 2 (Relational and Logical Operators)
- Multiply Large Numbers using Grid Method
- Bitwise right shift operators in Java
- Bitwise Operators in C/C++
- What are the differences between bitwise and logical AND operators in C/C++?
- Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs
- Find subsequences with maximum Bitwise AND and Bitwise OR
- Count ways to generate pairs having Bitwise XOR and Bitwise AND equal to X and Y respectively