Multiply a given Integer with 3.5 in C++

C++Server Side ProgrammingProgramming

To get the result of n * 3.5 we need to calculate (n * 2) + n + (n / 2). Moving the bits to left by 1 will give you n * 2 and moving the bits to right by will you n / 2. Add those to get the result.

n * 3.5 = (n * 2) + n + (n / 2)

You can submit different values of n to verify the above equation. Let's see some examples.

Input

2
7
10

Output

7
24
35

Algorithm

  • Initialise the number n.
  • Find the n * 2 using left shift bitwise operator
  • Find the n / 2 using right shift bitwise operator.
  • Add both the above values along with n to get the result.
  • Return the result.

It's a straightforward problem with the above steps.

Implementation

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

#include <bits/stdc++.h>
using namespace std;
int getTheResult(int x) {
   return (x << 1) + x + (x >> 1);
}
int main() {
   int n = 10;
   cout << getTheResult(n) << endl;
   return 0;
}

Output

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

35
raja
Published on 01-Jul-2021 07:01:12
Advertisements