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).
Input
The 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.
Output
One integer indicating the value of f(n)%m.
Sample Input
2
24 20
25 20
Sample Output
16
5
思路:由欧拉降幂公式有,
故有,假设都 小于对应的 欧拉函数值.
所以在快速幂的时候不是直接取模,而是 % mod + mod .... f() 函数求得是次幂,所以是在快速幂的时候做操作
Code:
#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define INT(t) int t; scanf("%d",&t)
using namespace std;
LL Euler(LL n){
LL ans = n;
for(LL i = 2;i * i <= n;++ i){
if(n % i == 0){
ans = ans / i * (i - 1);
while(n % i == 0)
n /= i;
}
}
if(n > 1) ans = ans / n * (n - 1);
return ans;
}
LL pow(LL a,LL b,LL mod){
LL ans = 1;
while(b){
if(b & 1){
ans *= a;
if(ans >= mod)
ans = ans % mod + mod;
}
b >>= 1;
a *= a;
if(a >= mod)
a = a % mod + mod;
}
return ans;
}
LL f(LL n,LL phim){
if(n == 0){
return 1LL;
}
LL tmp = f(n / 10,Euler(phim));
return pow(n % 10,tmp,phim);
}
int main() {
int t; scanf("%d",&t);
while(t --){
LL n,m; scanf("%lld%lld",&n,&m);
printf("%lld\n",f(n,m) % m);
}
return 0;
}