计算机内乘法运算极其消耗时间,下面通过位运算提高效率
A.
用位运算求乘法提高运算速度。
算法描述:
1. let v=vrvr-1…v1v0 be the binary represention of v,where the mostsignificant bit vr of vis 1.(r为下标)
2. set x=g;
3. for i from r-1 down to 0 do
3.1 set x<<=1
3.2 if vi=1,then set x=g+x .
4. output x.
具体算法:
int km(int v, int g){
int x = v;
int w = (int)floor(log(v) / log(2)) -1;
int e = 1 << w;
for(int i=w; i>=0; i--){
x <<= 1;
if(m & e) //测试k的第i位是否为1.
x += g;
e >>= 1;
}
return x;
}
B.用位运算求乘方模:g^v mod m
算法描述:
1. let v=vrvr-1…v1v0 be the binary represention of v,where the mostsignificant bit vr of vis 1.
2. set x=g;
3. for i from r-1 down to 0 do
3.1 set x=x2 mod m.
3.2 if vi=1,then set x=gx mod m.
4. output x.
__int64gvmm(__int64 g, __int64 v, __int64 m){
int w = (int)floor(log(v) / log(2)) -1;
__int64 e = 1 << w;
__int64 x = g;
for(int i=w; i>=0; i--){
x = (x * x) % m; //此处可优化,用上面的位乘法
if(v & e){
x = (g * x) % m; //此处可优化,用上面的位乘法
}
e >>= 1;
}
return x;
}