两个矩阵相乘的乘法次数
The problem is we have two integer numbers and find the multiplication of them without using the multiplication operator. This problem can be solved using the Russian peasant algorithm. Assume the two given numbers are m and n. Initialize mul with 0 and repeat following steps while n is greater than zero :
问题是我们有两个整数,并且不使用乘法运算符就可以找到它们的乘法 。 使用俄罗斯农民算法可以解决此问题。 假设两个给定的数字是m和n 。 用0初始化mul并在n大于零时重复以下步骤:
Add m to mul, if n is odd
如果n为奇数,则将m加到mul中
Double the value of m and half the value of n.
将m的值加倍,将n的值减半。
Here we use properties of << (left shift) and >> (right shift) operators for doubling the value of m and for dividing the value of ‘n by 2.
在这里,我们使用<< (左移)和>> (右移)运算符的属性将m的值加倍,并将' n的值除以2。
Reference: Russian peasant multiplication
参考: 俄罗斯农民繁殖
C ++程序实现俄罗斯农民算法 (C++ program to implement Russian peasant algorithm)
#include <iostream>
using namespace std;
int Multiply(int m, int n)
{
int mul=0;
while (n > 0)
{
// if n is odd
if (n & 1) mul = mul + m;
// Double 'm' and halve 'n'
m = m << 1;
n = n >> 1;
}
return mul;
}
int main() {
int ans;
ans=Multiply(2,3);
cout<<"Multiplication of 2 and 3 = "<<ans<<endl;
ans=Multiply(10,10);
cout<<"Multiplication of 10 and 10 = "<<ans<<endl;
return 0;
}
Output
输出量
Multiplication of 2 and 3 = 6
Multiplication of 10 and 10 = 100
翻译自: https://www.includehelp.com/cpp-programs/multiply-two-numbers-without-using-multiplication-operator.aspx
两个矩阵相乘的乘法次数