Fast exponentiation modulo


                     J - A^B mod C

  FZU-1752 

Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).

Input

There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.

Output

For each testcase, output an integer, denotes the result of A^B mod C.

Sample Input
3 2 4
2 10 1000
Sample Output
1
24


Idea: take the modulo of the exponentiation quickly, because the number is very large, the routine must time out.



The original fast exponentiation simple template (the number will overflow directly when used here):

//Seek(a^b)%c  
int qmod (int a, int b, int c)  
{  
    int res = 1;  
    for ( ; b; b >>= 1)  
    {  
        if (b & 1)  
            res = (LL)res * a % c;   
        a = (LL)a * a % c;  
    }  
    return res;  
}  
Fast power + fast product + detailed code processing.
①When judging parity, use bit operation processing
②When dealing with fetching, use subtraction instead of %.
Fast Product: Multiplication becomes addition in fast exponentiation.

The fast exponentiation algorithm relies on the following obvious formula:


ac code:

		#include<cstdio>
		#include<iostream>
		#include <string>
		#include<algorithm>
		#include<map>
		#include<set>
		#include<cstring>
		#include<cmath>
		#include<queue>
		#define ll long long int
		using namespace std;
		ll fun(ll a, ll b, ll c) {
			ll res = 0;
			while(b) {
				if(b & 1) {
					res = res + a;
					if(res >= c) {
						res = res - c;
					}
				}
				a  = a+ a;
				if(a >= c) {
					a = a - c;
				}
				b >>= 1;
			}
			return res;
		}
		int main(void) {
			ll a, b, c;
			ll res;
			while(~scanf("%lld%lld%lld", &a, &b, &c)) {
				a = a % c;
				res = 1;
				while(b) {
					if(b & 1) {
						res = fun(res,a,c); 		
					}
					a = fun(a, a, c);
					b >>= 1;
				}
				printf("%lld\n", res);	
			}
			return 0;
		}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324696341&siteId=291194637