两个矩阵相乘的乘法次数_C ++程序将两个数字相乘而不使用乘法运算符

本文介绍了一种不使用乘法运算符进行整数乘法的方法——俄罗斯农民算法。通过使用位运算符,如左移和右移,算法能有效地计算两个整数的乘积。文章提供了详细的步骤说明和C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两个矩阵相乘的乘法次数

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大于零时重复以下步骤:

  1. Add m to mul, if n is odd

    如果n为奇数,则将m加到mul中

  2. 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

两个矩阵相乘的乘法次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值