Multiply a given Integer with 3.5 in C++

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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
Updated on 25-Oct-2021 05:48:06

Advertisements