Home Previous year paper Algorithms Notes About us
Efficient way to multiply with 7

Let's derive an expression to multiply a number with 7 using bitwise operator. Let N be the number that we want to multiply with 7.

N x 7 = N + N + N + N + N + N + N

N x 7 = N + N + N + N + N + N + N + (N - N)

N x 7 = (N + N + N + N + N + N + N + N) - N

N x 7 = 8xN - N

As we know that, left shifting any number by one bit multiply it by 2. Hence, multiplying any number with 8 is equivalent to right shifting it by 3 bits(For Example : NX3 = N << 3). Replacing 8xN in above statement by 8 << 3.

N x 7 = (N << 3) - N

WARNING !!!!

This approach can only be used to multiply integers or char by 7 because bitwise Operators can only be applied on char and integer operands. We cannot use bitwise operators with float, double, long double, void and other user define complex data types.

Implementation

# include < bits/stdc++.h >

using namespace std;

//c++ implementation

long multiplyBySeven(long n)

{

/* Note the inner bracket here. This is needed

because precedence of '-' operator is higher

than '<<' */

return ((n<<3) - n);

}

/* Driver program to test above function */

int main()

{

long n = 4;

cout<
return 0;

}

Output:

28

Time Complexity:

O(1)

Space Complexity:

O(1)