C 基于位移位的乘法算法
在寻找2个大数相乘的有效算法时,在一个论坛上遇到了以下c方法:-C 基于位移位的乘法算法,c,algorithm,multiplication,C,Algorithm,Multiplication,在寻找2个大数相乘的有效算法时,在一个论坛上遇到了以下c方法:- ... typedef unsigned long long ULL; ULL multiply (ULL a,ULL b) { ULL result = 0; while(a > 0) { if(a & 1) { result += b; } a >>= 1;
...
typedef unsigned long long ULL;
ULL multiply (ULL a,ULL b)
{
ULL result = 0;
while(a > 0)
{
if(a & 1)
{
result += b;
}
a >>= 1;
b <<= 1;
}
return result;
}
...
。。。
typedef无符号长ULL;
ULL乘法(ULL a,ULL b)
{
结果=0;
而(a>0)
{
如果(a&1)
{
结果+=b;
}
a>>=1;
b它迭代a
中的所有1位,添加b
移位适当的量
首先,请注意,如果a
是11001
,则可以将其视为10000
+1000
+1
,因此a*b
是(10000*b)+(1000*b)+(1*b)
。
然后,请注意,10000*b
就是b哇,这是一个很好的算法,与我们手工做的类似:
123*
456=
6*(123)+
50*(123)+ //this means one digit shift, nice and easy
400*(123) //this means two digits shift, nice and easy
那么让我们来做二进制:
101* //b
110= //a
0*(101)+
10*(101)+ //=1*(1010) //one digit shift
100*(101) //=1*(10100) //two digits shift
a通过以下方式右移以访问其第一位:if(a&1)
b为每个位置向左移位,以执行与上述相同的一位数移位
这正是我们手动乘法时所做的操作
我建议使用uint64\u tfrom
#include<stdint.h>
#包括
要获得良好且清晰的编码样式:
#include<stdint.h>
uint64_t multiply(uint64_t a, uint64_t b)
{
uint64_t result = 0;
while (a > 0)
{
if (a & 1)
{
result += b;
}
a >>= 1;
b <<= 1;
}
return result;
}
int main() {
uint64_t a = 123;
uint64_t b = 456;
uint64_t c = multiply(a, b);
}
#包括
uint64\u t乘法(uint64\u t a,uint64\u t b)
{
uint64_t结果=0;
而(a>0)
{
如果(a&1)
{
结果+=b;
}
a>>=1;
注:有些CPU的移位运算速度非常慢——例如68008。因此,您的里程数可能会有所不同。“从而使其更快”——在某种程度上,该算法与您在学校学习的长乘法算法不同,只是第一个操作数取基数2。它有时被称为“俄语乘法”