快速乘:
ull mul(ull a,ull b,ull p){
ull c=(long double)a/p*b;
return ((a*b-p*c)%p+p)%p;
}
__int128:
ull mull(ull a,ull b,ull p){
return (__int128)a*b%p;
}
龟速乘:
ull mulll(ull a,ull b,ull p){
ull ans=0;
while(b){
if(b&1) ans=(ans+a)%p;
a=(a+a)%p;
b>>=1;
}
return ans;
}
执行如下代码(108 次乘运算):
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
ull a,b,p;
ull mul(ull a,ull b,ull p){
ull c=(long double)a/p*b;
return ((a*b-p*c)%p+p)%p;
}
ull mull(ull a,ull b,ull p){
return (__int128)a*b%p;
}
ull mulll(ull a,ull b,ull p){
ull ans=0;
while(b){
if(b&1) ans=(ans+a)%p;
a=(a+a)%p;
b>>=1;
}
return ans;
}
int main(){
ull n=1e8,ans=0;
ull a=846351184365,b=321368413651,c=654676851324;
for(int T=0;T<n;T++) ans+=mul(a,b,c); // or mull(a,b,c) or mulll(a,b,c)
cout<<(double)clock()/CLOCKS_PER_SEC;
return 0;
}
/*
0.679
1.038
15.743
*/
输出分别为:0.679,1.038,15.743。
__int128 耗时竟比快速乘多了 52.87%!什么情况?