📜  在不使用乘法运算符的情况下将变量与常量相乘

📅  最后修改于: 2021-05-04 22:24:56             🧑  作者: Mango

我们知道每个数字都可以表示为2的幂的和(或差),因此我们可以做的是将常数表示为2的幂的和。
为此,我们可以使用按位左移运算符。当一个数字按位左移时,每个位移将乘以2。
例如,假设我们要将变量“ a”乘以10,那么我们可以做的是

a = a << 3 + a << 1;

表达式a << 3将a乘以8 ans表达式a << 1将其乘以2。
所以基本上我们这里是a = a * 8 + a * 2 = a * 10
同样,要乘以7,我们可以做的是

a = a<<3 - a;
or
a = a<<2 + a<<1 + a;

这两个语句都将a乘以7。

C++
#include
using namespace std;
 
// Returns n * 7
int multiplyBySeven(int n)
{
    // OR (n << 2) + (n << 1) + n
    return (n << 3) - n;
}
 
// Returns n * 12
int multiplyByTwelve(int n)
{
    return (n << 3) + (n << 2);
}
 
int main()
{
    cout << multiplyBySeven(5) << endl;
    cout << multiplyByTwelve(5) << endl;
    return 0;
}


Java
class GFG {
     
    // Returns n * 7
    static int multiplyBySeven(int n)
    {
         
        // OR (n << 2) + (n << 1) + n
        return (n << 3) - n;
    }
 
    // Returns n * 12
    static int multiplyByTwelve(int n)
    {
        return (n << 3) + (n << 2);
    }
     
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(multiplyBySeven(5));
        System.out.println(multiplyByTwelve(5));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to Multiplying a
# variable with a constant
 
# Returns n * 7
def multiplyBySeven(n):
     
    # OR (n << 2) + (n << 1) + n
    return (n << 3) - n
 
# Returns n * 12
def multiplyByTwelve(n):
    return (n << 3) + (n << 2)
     
# Driver code
print(multiplyBySeven(5))
print(multiplyByTwelve(5))
 
# This code is contributed by Anant Agarwal.


C#
// C# program to Multiplying a
// variable with a constant
using System;
 
class GFG
{
    // Returns n * 7
    static int multiplyBySeven(int n)
    {
        // OR (n << 2) + (n << 1) + n
        return (n << 3) - n;
    }
      
    // Returns n * 12
    static int multiplyByTwelve(int n)
    {
        return (n << 3) + (n << 2);
    }
     
    // Driver code
    public static void Main()
    {
        Console.WriteLine(multiplyBySeven(5));
        Console.WriteLine(multiplyByTwelve(5));
    }
}
 
// This code is contributed by Anant Agarwal.


PHP


Javascript


输出 :

35
60