Multiplying a variable with a constant without using multiplication operator
As we know that every number can be represented as sum(or difference) of powers of 2, therefore what we can do is represent the constant as a sum of powers of 2.
For this purpose we can use the bitwise left shift operator. When a number is bitwise left shifted it is multiplied by 2 for every bit shift.
For example, suppose we want to multiply a variable say “a” by 10 then what we can do is
a = a << 3 + a << 1;
The expression a << 3 multiplies a by 8 ans expression a<<1 multiplies it by 2.
So basically what we have here is a = a*8 + a*2 = a*10
Similarly for multiplying with 7 what we can do is
a = a<<3 - a;
or
a = a<<2 + a<<1 + a;
Both these statements multiply a by 7.
C++
#include<iostream>
using namespace std;
int multiplyBySeven( int n)
{
return (n << 3) - n;
}
int multiplyByTwelve( int n)
{
return (n << 3) + (n << 2);
}
int main()
{
cout << multiplyBySeven(5) << endl;
cout << multiplyByTwelve(5) << endl;
return 0;
}
|
Java
class GFG {
static int multiplyBySeven( int n)
{
return (n << 3 ) - n;
}
static int multiplyByTwelve( int n)
{
return (n << 3 ) + (n << 2 );
}
public static void main(String[] args)
{
System.out.println(multiplyBySeven( 5 ));
System.out.println(multiplyByTwelve( 5 ));
}
}
|
Python3
def multiplyBySeven(n):
return (n << 3 ) - n
def multiplyByTwelve(n):
return (n << 3 ) + (n << 2 )
print (multiplyBySeven( 5 ))
print (multiplyByTwelve( 5 ))
|
C#
using System;
class GFG
{
static int multiplyBySeven( int n)
{
return (n << 3) - n;
}
static int multiplyByTwelve( int n)
{
return (n << 3) + (n << 2);
}
public static void Main()
{
Console.WriteLine(multiplyBySeven(5));
Console.WriteLine(multiplyByTwelve(5));
}
}
|
PHP
<?php
function multiplyBySeven( $n )
{
return ( $n << 3) - $n ;
}
function multiplyByTwelve( $n )
{
return ( $n << 3) + ( $n << 2);
}
echo multiplyBySeven(5), "\n" ;
echo multiplyByTwelve(5), "\n" ;
?>
|
Javascript
<script>
function multiplyBySeven(n)
{
return (n << 3) - n;
}
function multiplyByTwelve(n)
{
return (n << 3) + (n << 2);
}
document.write(multiplyBySeven(5) + "<br>" );
document.write(multiplyByTwelve(5) + "<br>" );
</script>
|
Output :
35
60
Time Complexity: O(1)
Auxiliary Space: O(1)
We just need to find the combination of powers of 2. Also, this comes really handy when we have a very large dataset and each one of them requires multiplication with the same constant as bitwise operators are faster as compared to mathematical operators.
Last Updated :
05 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...