HDU 2837 Calculation

Calculation

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


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
 

Recommend
gaojie


题意:给一个公式f(n)=f(n%10)^f(n/10),f(0)=1,求f(n)
f(n)只能递归计算,但是x^y中y的值可能过大,这里要用到一个公式x^y%m=x^(y%phi(m)+phi(m))%m,可参考:http://blog.csdn.net/doyouseeman/article/details/51863382,当x与m互质时就是一种特殊情况,x^phi(m)=1,这个公式只能在y>phi(m)的时候使用


#pragma comment(linker,"/STACK:1024000000,1024000000”)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<map>
#include<cmath>
#include<vector>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;

#define pi acos(-1.0)
#define eps 1e-10
#define pf printf
#define sf scanf
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
#define e tree[rt]
#define _s second
#define _f first
#define all(x) (x).begin,(x).end
#define mem(i,a) memset(i,a,sizeof i)
#define for0(i,a) for(int (i)=0;(i)<(a);(i)++)
#define for1(i,a) for(int (i)=1;(i)<=(a);(i)++)
#define mi ((l+r)>>1)
#define sqr(x) ((x)*(x))

const int inf=0x3f3f3f3f;
ll n,m;
int t;

ll ouler(ll x)
{
    ll ans=x;
    for(ll i=2;sqr(i)<=x;i++)
        if(!(x%i))
        {
            ans=ans/i*(i-1);
            while(!(x%i))x/=i;
        }
    if(x>1)ans=ans/x*(x-1);
    return ans;
}

ll quick(ll n,ll p,ll m)
{
    ll ans=1;
    while(p)
    {
        if(p&1)
        {
            ans=ans*n;
            if(ans>m)
                ans=ans%m+m;
        }
        n=n*n;
        if(n>m)n=n%m+m;
        p>>=1;
    }
    return ans;
}

ll solve(ll n,ll m)
{
    if(n<10)return n;
    ll p=solve(n/10,ouler(m));
    return quick(n%10,p,m);
}

int main()
{
    sf("%d",&t);
    while(t--)
        sf("%I64d%I64d",&n,&m),pf("%I64d\n",solve(n,m)%m);
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值