HDU - 2837 Calculation (欧拉降幂,a ^ (b ^ c)以及更高)

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

思路:由欧拉降幂公式有,a^{b}\%m=\left\{\begin{matrix} a^{b\%\varphi(m)} & b < \phi(m) \\ a^{b\%\varphi(m)+\varphi(m)} & b>=\phi(m) \end{matrix}\right.

故有a^{b^{c}}\%m=a^{b^{c\%\varphi(\varphi(m))}\%\varphi(m)}\%m,假设都 小于对应的 欧拉函数值.

所以在快速幂的时候不是直接取模,而是   % 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值