快速幂取模


                     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


思路:快速幂取模,因为数很大,常规肯定超时。



原来的快速幂取模简单模板(用在这里数会直接溢出):

//求(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;  
}  
快速幂+快速积+细节代码处理。
①判断奇偶性的时候要用位运算处理
②处理取摸的时候不用%而用减法。
快速积:快速幂中乘法变加法。

快速幂算法依赖于以下明显的公式:


ac代码:

		#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;
		}


猜你喜欢

转载自blog.csdn.net/xiao__jia__jia/article/details/80038429