For any given two numbers n and m, you have to find n*m without using any multiplication operator.
Input: n = 25 , m = 13 Output: 325 Input: n = 50 , m = 16 Output: 800
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.
Check for every set bit in the binary representation of m and for every set bit left shift n, count times where count if place value of the set bit of m and add that value to answer.
Time Complexity : O(log n)
Russian Peasant (Multiply two numbers using bitwise operators)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- How to swap two numbers without using a temporary variable?
- Count total set bits in all numbers from 1 to n
- Add two numbers without using arithmetic operators
- Bitwise right shift operators in Java
- Russian Peasant (Multiply two numbers using bitwise operators)
- Subtract two numbers without using arithmetic operators
- Calculate 7n/8 without using division and multiplication operators
- Find XOR of two number without using XOR operator
- Print first n numbers with exactly two set bits
- Find Two Missing Numbers | Set 2 (XOR based solution)
- Check if a number can be expressed as a sum of consecutive numbers
- Multiply a number with 10 without using multiplication operator
- Multiplying a variable with a constant without using multiplication operator
- Compare two integers without using any Comparison operator
- Count smaller numbers whose XOR with n produces greater value