码迷,mamicode.com
首页 > 其他好文 > 详细

hdu_2837_Calculation(欧拉函数,快速幂求指数循环节) (待查

时间:2017-11-26 21:49:29      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:hat   tput   ace   long   inpu   pos   ons   ret   osi   

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).

InputThe 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.OutputOne integer indicating the value of f(n)%m.Sample Input

2
24 20
25 20

Sample Output

16
5


指数循环节题目就是欧拉函数加快速幂。
根据欧拉定理 A^x mod C=A^(x mod phi(C) (x>=C)
本题不能模取零,相关证明及推理有待查证。
A^x mod C =A^(x mod phi(C)+ phi(C)) (x>=C)

#include <iostream>
#include<cstdio>
using namespace std;
#define ll long long
ll phi(ll c)
{
    ll ans = c;
    for(int i = 2; i*i <= c; i++) {
        if(c%i == 0){
            ans -= ans/i;
            while(c%i == 0) c /= i;
        }
    }
    if(c > 1) ans -= ans/c;
    return ans;
}
ll quick_mod(ll a, ll b, ll mod)
{
    if(a >= mod) a = a%mod + 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)
{
    ll p = phi(m);
    if(n == 0) return 1;
    ll index = solve(n/10, p);

    return quick_mod(n%10, index, m);
}
int main()
{
    ll n, m, T;
    cin >> T;
    while(T--){
        scanf("%I64d%I64d", &n, &m);
        printf("%I64d\n", solve(n,m)%m);
    }
    return 0;
}

  

hdu_2837_Calculation(欧拉函数,快速幂求指数循环节) (待查

标签:hat   tput   ace   long   inpu   pos   ons   ret   osi   

原文地址:http://www.cnblogs.com/ygtzds/p/7900407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!