Multiply any Number with using Bitwise Operator in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going write a program that multiplies the given two numbers using bitwise operators.

The left shift (<<) operator is used for the multiplication whereas the right shift (>>) is used for the division.

The multiplication of two numbers x, y can be written as x * y = (x * 2) * (y / 2) if y is even else it's equal to x * y = (x * y) * (y / 2) + x.

So whenever the second number becomes odd, add the first number to the result. Let's see the steps to solve the problem.

Algorithm

  • Initialise two numbers.
  • Write a loop that iterates till the second number becomes 0.
    • If the second number is odd, then add the first number to the result.
    • Left shift first number by 1 bit.
    • Right shift second number by 1 bit.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int multiplyTwoNumbers(int a, int b) {
   int result = 0;
   while (b > 0) {
      if (b & 1) {
         result += a;
         }
      a = a << 1;
      b = b >> 1;
   }
   return result;
}
int main() {
   cout << multiplyTwoNumbers(75, 4) << endl;
   cout << multiplyTwoNumbers(90, 9) << endl;
   cout << multiplyTwoNumbers(83, 66) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

300
810
5478
raja
Published on 02-Jul-2021 11:01:35
Advertisements