ACM/ICPC 2019南京網絡賽 B.super_log (歐拉降冪)

題目鏈接

縮略題目

In Complexity theory, some functions are nearly O(1)O(1), but it is greater then O(1)O(1). For example, the complexity of a typical disjoint set is O(nα(n))O(nα(n)). Here α(n)α(n) is Inverse Ackermann Function, which growth speed is very slow. So in practical application, we often assume α(n) \le 4α(n)≤4.

計蒜客上的LaTeX複製後搞得我很難受,不想一一改了,具體題目點題目鏈接吧。

題意

很複雜,但意思就是求一個:
aaaa...mod(m)a^{a^{a^{a^{...}}}} mod(m)
共有b個a。

我的理解

歐拉降冪:
當a與m互質,則:
在這裏插入圖片描述
當a與m不互質,則:
在這裏插入圖片描述
因爲a和m不保證互質,所以要考慮a與m的互質情況。

phi(m)=1phi(m) = 1時,歐拉降冪可以提前結束,則直接返回。

代碼

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll a,b,mod;

ll mod_pow(ll a, ll n, ll mod) {
	a %= mod;
	ll ret = 1;
	while (n) {
		if (n & 1) ret = (ret*a) % mod;
		a = a*a%mod;
		n >>= 1;
	}
	return ret;
}

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

ll dfs(ll n,ll m,int time){
	if(m == 1)	return 0;
	if(time==0)	return 1;
	ll phim = euler(m);
	ll exp = dfs(n,phim,time-1);
	if(exp<phim && exp)
		return mod_pow(n,exp,m);
	else
		return mod_pow(n,exp+phim,m);
}

int main(){
	int t;cin>>t;
	while(t--){
		scanf("%lld%lld%lld",&a,&b,&mod);
		ll ans = dfs(a,mod,b);
		printf("%lld\n",ans);
	}
	
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章