Multiply a number by 15 without using * and / operators in C++

C++Server Side ProgrammingProgramming

We can using left shift (<<) operator to multiply with 15. If we left shift 1, then we are multiplying it with 2.

If we left shift the given number with 4, then we will get the 16 * n. Subtracting the given number from 16 * n will result in 15 * n.

Or

We can also divide it as 8 * n + 4 * n + 2 * n + n. You can easily multiply the powers of 2 using left shift.

Algorithm

  • Initialise the number n.
  • Find the n << 4 to get 16 * n.
  • Subtract n from the above result.
  • Return the final answer.

Implementation

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

#include <bits/stdc++.h>
using namespace std;
long long getMultiplicationResult(long long n) {
   return (n << 4) - n;
}
int main() {
   long long n = 15;
   cout << getMultiplicationResult(n) << endl;
   return 0;
}

Output

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

225
raja
Published on 01-Jul-2021 07:04:46

Advertisements