UVA550 Multiplying by Rotation

本文介绍了一种特殊的乘法运算——旋转乘法,并通过模拟的方式实现了这一算法。该算法的特点在于将乘法运算的结果通过旋转操作来表示,具体表现为将乘积的最低位移动到最高位。

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

思路:简单的模拟乘法


#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
	int n,m,k;
	while(scanf("%d%d%d",&m,&k,&n)!=EOF)
	{
		int count = 1,now=k,save=0,temp;
		while(now*n+save!=k)
		{
			temp=now;
			now = (temp*n+save)%m;
			save = (temp*n+save)/m;
			count++;
		}
		printf("%d\n",count);
	}
}



Warning: Not all numbers in this problem are decimal numbers!
Multiplication of natural numbers in general is a cumbersome operation. In some cases however the
product can be obtained by moving the last digit to the front.
Example: 179487 * 4 = 717948
Of course this property depends on the numbersystem you use, in the above example we used the
decimal representation. In base 9 we have a shorter example:
17 * 4 = 71 (base 9)
as (9 * 1 + 7) * 4 = 7 * 9 + 1
Input
The input for your program is a textfile. Each line consists of three numbers separated by a space: the
base of the number system, the least significant digit of the first factor, and the second factor. This
second factor is one digit only hence less than the base. The input file ends with the standard end-of-file
marker.
Output
Your program determines for each input line the number of digits of the smallest first factor with the
rotamultproperty. The output-file is also a textfile. Each line contains the answer for the corresponding
input line.
Sample Input
10 7 4
9 7 4
17 14 12
Sample Output
6
2
4


### 不使用乘法运算的矩阵相乘方法 对于不依赖于传统乘法操作而实现矩阵相乘的需求,可以考虑利用加法和位移操作替代标准乘法。这种方法特别适用于二进制数值表示下的整数矩阵。 #### 使用加法与位移代替乘法 当处理两个较小规模的正整数时,可以通过重复累加的方式模拟乘法效果。例如,要计算 \(a \times b\) 可以通过将 a 加上自己共 b 次来完成。这种思路同样可应用于矩阵元素间的相互作用: 给定两个矩阵 A 和 B ,其中 A 的维度为 m×n 而 B 的维度为 n×p 。为了得到 C=AB 结果中的某个特定位置 c_{ij} 值,则需遍历 k 属于 {1,...,n} 并执行如下逻辑: - 初始化临时变量 temp 到零; - 对每一个非零项 a_{ik}, 将其对应的 b_{kj} 复制到一个新的向量 v 中; - 针对上述获得的每个 v[j], 执行 |v| 次自增操作至 temp 上;这里 |v| 表示取绝对值后的大小; - 更新目标矩阵 C 中对应的位置 c_{ij}=temp 。 此过程实际上就是把常规意义上的 “乘积求和” 替换成了一系列基于条件判断的选择性增量行为[^1]。 然而值得注意的是,在实际应用中完全摒弃硬件层面支持的传统算术指令并不现实也无必要——现代计算机体系结构已经高度优化了此类基础运算性能。因此除非有特殊需求或约束环境(比如某些嵌入式系统),通常不会刻意追求这种方式来进行大规模矩阵运算。 ```python def matmul_without_multiplication(A, B): rows_A = len(A) cols_A = len(A[0]) cols_B = len(B[0]) result = [[0 for _ in range(cols_B)] for __ in range(rows_A)] for i in range(rows_A): for j in range(cols_B): temp = 0 for k in range(cols_A): if A[i][k]: value_to_add = abs(B[k][j]) * (-1)**(B[k][j]<0) # Handle negative numbers while value_to_add != 0: sign = -1 if value_to_add < 0 else 1 value_to_add -= sign temp += A[i][k]*sign result[i][j] = temp return result ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值