HDU - 2837 Calculation(指数循环节+扩展欧拉定理)

传送门


扩展欧拉定理求解 f ( n ) = ( n % 10 ) f ( n / 10 ) , f ( 0 ) = 1 f(n)=(n\%10)^{f(n/10)},f(0)=1 f(n)=(n%10)f(n/10),f(0)=1,指数显然是会很大的,那么递归从最里层回溯即可,当指数过大时使用欧拉降幂。注意取模的数每次都递归 φ ( m ) \varphi(m) φ(m),然后判断当前的数和 φ ( m ) \varphi(m) φ(m)的大小判断是否需要加上 φ ( m ) \varphi(m) φ(m)

实际上 A C D r e a m e r ACDreamer ACDreamer的博客才是正解,但是网上很多题解都是特殊的快速幂,看不懂为什么当快速幂求得 0 0 0时必须加上 m m m,翻阅了很多资料都没找到答案。自己写了一下发现确实是正确的,如下面代码的注释,如果有大佬指出,不胜感激。

注意题目说明了 0 0 = 1 , 0 1 = 0 2 = . . . = 0 k = 0 0^0=1,0^1=0^2=...=0^k=0 00=1,01=02=...=0k=0

//
// Created by Happig on 2020/8/26
//
#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>

using namespace std;
#define fi first
#define se second
#define pb push_back
#define ins insert
#define Vector Point
#define lowbit(x) (x&(-x))
#define mkp(x, y) make_pair(x,y)
#define mem(a, x) memset(a,x,sizeof a);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double dinf = 1e300;
const ll INF = 1e18;
const int Mod = 1e9 + 7;
const int maxn = 2e5 + 10;

inline ll mul(ll a, ll b, ll p) {
     
    if (p <= 1000000000) return a * b % p;
    else if (p <= 1000000000000LL) return (((a * (b >> 20) % p) << 20) + (a * (b & ((1 << 20) - 1)))) % p;
    else {
     
        ll d = (ll) floor(a * (ld) b / p + 0.5);
        ll ret = (a * b - d * p) % p;
        if (ret < 0) ret += p;
        return ret;
    }
}

ll qkp(ll x, ll n, ll p) {
     
    if (x == 0) return n == 0;
    ll ans = 1;
    x %= p;
    while (n) {
     
        if (n & 1) ans = mul(ans, x, p);
        x = mul(x, x, p);
        n >>= 1;
    }
    return ans == 0 ? p : ans % p;   //为什么为0时就返回p
}

ll euler_phi(ll n) {
     
    int m = sqrt(n + 0.5);
    ll ans = n;
    for (int i = 2; i <= m; i++) {
     
        if (n % i == 0) {
     
            ans = ans / i * (i - 1);
            while (n % i == 0) n /= i;
        }
    }
    if (n > 1) ans = ans / n * (n - 1);
    return ans;
}

ll f(ll n, ll m) {
     
    if (n < 10) return n;
    return qkp(n % 10, f(n / 10, euler_phi(m)), m);
}

int main() {
     
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int t, n, m;
    cin >> t;
    while (t--) {
     
        cin >> n >> m;
        cout << f(n, m) % m << "\n";
    }
    return 0;
}

你可能感兴趣的:(数论)