hdu_2837_Calculation(欧拉函数,快速幂求指数循环节)
Assume that f(0) = 1 and 0^0=1. f(n) = (n%10)^f(n/10) for all n bigger than zero. Please calculate f(n)%m. (2 ≤ n , m ≤ 10^9, x^y means the y th power of x).
InputThe first line contains a single positive integer T. which is the number of test cases. T lines follows.Each case consists of one line containing two positive integers n and m.OutputOne integer indicating the value of f(n)%m.Sample Input
2 24 20 25 20
Sample Output
16 5
指数循环节题目就是欧拉函数加快速幂。
根据欧拉定理
A^x mod C =A^(x mod phi(C)+ phi(C)) (x>=C)
#include <iostream>
#include<cstdio>
using namespace std;
#define ll long long
ll phi(ll c)
{
ll ans = c;
for(int i = 2; i*i <= c; i++) {
if(c%i == 0){
ans -= ans/i;
while(c%i == 0) c /= i;
}
}
if(c > 1) ans -= ans/c;
return ans;
}
ll quick_mod(ll a, ll b, ll mod)
{
if(a >= mod) a = a%mod + mod; // 并不是直接%mod
ll ans = 1;
while(b){
if(b&1){
ans = ans*a;
if(ans >= mod) ans = ans%mod + mod;//**
}
a *= a;
if(a >= mod) a = a%mod + mod;//**
b >>= 1;
}
return ans;
}
ll solve(ll n, ll m)
{
ll p = phi(m);
if(n == 0) return 1;
ll index = solve(n/10, p);
return quick_mod(n%10, index, m);
}
int main()
{
ll n, m, T;
cin >> T;
while(T--){
scanf("%I64d%I64d", &n, &m);
printf("%I64d\n", solve(n,m)%m);
}
return 0;
}

浙公网安备 33010602011771号