hdu2837 Calculation a^b%p=a^(b%phi(p)+phi(p))%p

Calculation

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 873    Accepted Submission(s): 192


Problem Description
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


 

Source
2009 Multi-University Training Contest 3 - Host by WHU


 

Recommend
gaojie

 

a^b%p=a^(b%phi(p)+phi(p))%p   b>=phi(p)

#include<iostream>
#include<cstdlib>
#include<stdio.h>
#define ll __int64
using namespace std;
ll powermod(ll a,ll b,ll p)
{
    ll res=1;
    while(b)
    {
        if(b&1)res=res*a%p;
        b>>=1;
        a=a*a%p;
    }
    return res;
}
ll get_phi(int m)
{
    ll res=1;
    for(int i=2;i*i<=m;i++)
    {
        if(m%i==0)
        {
            m/=i;
            res*=(i-1);
            while(m%i==0){m/=i;res*=i;}
        }
    }
    if(m!=1)
    res*=(m-1);
    return res;
}
ll check(int a,int b,int p)
{
    ll res=1;
    for(int i=1;i<=b;i++)
    {
        res*=a;
        if(res>=p) return res;
    }
    return res;
}
ll dfs(int n,int m)
{
    ll phi=get_phi(m);
    if(n<10)
    return n;
    ll x=dfs(n/10,phi);
    ll yy=check(n%10,x,m);
    if(yy>=m)
    {
        ll res=powermod(n%10,x+phi,m);
        if(res==0)
        res+=m;
        return res;
    }
    else
    return yy;
}
int main()
{
    int n,m,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        printf("%I64d\n",dfs(n,m)%m);
    }
    return 0;
}


 

你可能感兴趣的:(BI)