Prepared for New Acmerhttp: // acm.hdu.edu.cn/showproblem.php? Pid = 1420 Montgomery power mode idea:
In power modulo operations, a power modulo operation is usually used to convert a power modulo operation to a Multiplication Modulo operation. There are two formulas:
1) a * B % n = (a % n) * (B % n) % n
2) (a + B) % n = (a % n + B % n) % n
When we calculate D = C ^ 15% N, there are:
C1 = C * C % N = C ^ 2% N
C2 = C1 * C % N = C ^ 3% N
C3 = C2 * C2 % N = C ^ 6% N
C4 = C3 * C % N = C ^ 7% N
C5 = C4 * C4 % N = C ^ 14% N
C6 = C5 * C % N = C ^ 15% N
Therefore, power modulo operations can be converted to Multiplication Modulo operations. Continue to see, we will find that D = C ^ E % N is required to know when E can be divided into 2, and do not need to perform the operations of one or two again, you only need to verify whether the binary bit of E is 0 or 1.
Code:
#include <cstdio>__int64 fun(__int64 A,__int64 B,__int64 C){__int64 k = 1; A%=C;while(B>=1){if((B&1)!=0)k = (k*A)%C; B>>= 1;A = A*A%C;}return k;}int main(int argc, char *argv[]){int n;scanf("%d",&n);__int64 A,B,C;while(n--){scanf("%I64d%I64d%I64d",&A,&B,&C);printf("%I64d\n",fun(A,B,C));}return 0;}
Common Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> # include <cmath> # include <string> # include <iomanip> using namespace std; int main (int argc, char * argv []) {int n; scanf ("% d", & n); int A, B, C; while (n --) {scanf ("% d", & A, & B, & C); _ int64 ans = 1; for (int I = 1; I <= B; I ++) {ans * = A; ans % = C; // note that the remainder of the request is required. Otherwise, data overflow is easy ;} printf ("% I64d \ n", ans);} return 0 ;}