hdu 2837 Calculation(指数循环节+欧拉函数)

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
题意:

让求公式 f(n)=(n%10)f(n10)%m f ( n ) = ( n % 10 ) f ( n 10 ) % m

分析:

很明显 f(n10) f ( n 10 ) 可能会很大,因此我们需要降幂,因为m不一定是素数因此不能用费马小定理降幂,只能用欧拉函数降幂

ax(mod m)=ax mod ϕ(m)+ϕ(m)(mod m) a x ( m o d   m ) = a x   m o d   ϕ ( m ) + ϕ ( m ) ( m o d   m )

注意在求x的时候,实际上是是通过递归用快速幂求出来的,因此快速幂的时候一定要取模再加模,否则不对我他妈。。坑了我一上午wa了11发

code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll Euler(ll n){
    ll res = n,a = n;
    for(ll i = 2; i * i <= a; i++){
        if(a % i == 0){
            res = res / i * (i - 1);
            while(a % i == 0) a /= i;
        }
    }
    if(a > 1) res = res / a * (a - 1);
    return res;
}
ll q_pow(ll a,ll b,ll mod){
    ll ans = 1;
    while(b){
        if(b & 1){
            ans = ans * a;
            if(ans > mod) ans = ans % mod + mod;//注意!!必须加模
        }
        a = a * a;
        if(a > mod) a = a % mod + mod;//注意!!必须加模
        b >>= 1;
    }
    return ans;
}
ll f(ll n,ll m){
    if(n < 10) return n;
    ll phi = Euler(m);
    ll t = f(n/10,phi),ans;
    ans = q_pow(n%10,t,m);
    return ans;
}
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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值