HDU2837 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(n/10)计算f(n)
思路:a^x=a^(x%phi(c)+phi(c)) (mod c) 
又是这个公式,对于这个公式只有在x>phi(c)的时候成立,之前没注意
和前面一个题目是非常类似的,uva10692,都是求a^b^c……%mod
递归求解
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<cmath>
using namespace std;
#define ll long long
//#define mod 1000000007
ll Oula(ll n)
{
    ll ans=n;
    for(int i=2;i<=(double)sqrt(n*1.0);i++)
    {
        if(n%i==0)
            ans=ans*(1.0-1.0/i);
        while(n%i==0)
            n=n/i;
    }
    if(n>1)
        ans=ans*(1.0-1.0/n);
    return ans;
}
ll ppow(ll a, ll b, ll mod)
{
    if(a>=mod)
    a=a%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)
{
    if(n==0)
        return 1;
    if(n<10)
        return n;
    ll p=Oula(m);
    ll temp=solve(n/10,p);
    return ppow(n%10,temp,m);
}
int main()
{
    ll n,m;
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        cout<<solve(n,m)%m<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值