标签:
在实际应用中为了防止数据爆出,在计算a*b%m和x^n%m时,可以采用此方法。在数论中有以下结论:
a*b%m=((a%m)*(b*m))%m ;
(a+b)%m=(a%m+b%m)%m ;
_int64 Plus(_int64 a, _int64 b,_int64 m) { //计算a*b%m _int64 res = 0; while (b > 0) { if (b & 1) res=(res+a)%m; a = (a << 1) % m; b >>= 1; } return res; } _int64 Power(_int64 x, _int64 n,_int64 m) { //计算x^n%m _int64 res=1; while (n > 0) { if (n & 1) res=(res*x)%m; x = (x*x)%m; n>>= 1; } return res; }
例题:HDU 5666
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 748 Accepted Submission(s): 290
#include<iostream> using namespace std; _int64 Plus(_int64 a, _int64 b, _int64 m); int main() { _int64 p,q,T; cin >> T; while (T--) { cin >> q >> p; cout << Plus((q-1)%2, q-2, p) << endl; } return 0; } _int64 Plus(_int64 a, _int64 b,_int64 m) { _int64 res = 0; while (b > 0) { if (b & 1) res = (res + a) % m; a = (a+a) % m; b >>= 1; } return res; }
标签:
原文地址:http://www.cnblogs.com/td15980891505/p/5402832.html