幂塔个位数的计算

幂塔个位数的计算

解题思路:欧拉降幂。

在这里插入图片描述

只需要保留最后两位,其实也不需要计算那么多层,最多100层就可以了,欧拉降幂递归求。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<int,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 1e6+10;
const ll mod = 1e9+7;
const double PI = acos(-1.0);
const double eps = 1e-4;

inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){str+=s;s=getchar();}return str;}
int random(int n){return (int)(rand()*rand())%n;}
void writestring(string s){int n = s.size();for(int i = 0;i < n;i++){printf("%c",s[i]);}}


ll phi[N];
void euler(int n){
    phi[1] = 1;
    for(int i = 2;i <= n;i++) phi[i] = i;
    for(int i = 2;i <= n;i++){
        if(phi[i] == i){
            for(int j = i;j <= n;j += i){
                phi[j] = phi[j]/i*(i-1);
            }
        }
    }
}


ll fast_power(ll a,ll b,ll p){
    ll res=1;
    while(b){
        if(b&1) {
            res=res*a>p?res*a%p+p:res*a;
        }
        b>>=1;
        a=a*a>p?a*a%p+p:a*a;
    }
    return res;
}
ll solve(ll a,ll b,ll p){

    if(b == 0||p==1) return 1;
    if(__gcd(a,p) == 1) {
        return fast_power(a,solve(a,b-1,phi[p]),p);
    }else {
        int x = solve(a,b-1,phi[p]);
        if(x < phi[p]) return fast_power(a,x,p);
        return fast_power(a,x%phi[p]+phi[p],p);
    }
}
int main(){
    srand((unsigned)time(NULL));
    euler(100000);
    string s = readstring(),t = readstring();
    ll a = 0,b=0;
    for(int i = max(0,(int)s.size()-2);i < s.size();i++){
        a = a*10+(s[i]-48);
    }
    if(t.size() >= 3) b = 100;
    else {
        for(int i = 0;i < t.size();i++){
            b = b*10+(t[i]-48);
        }
    }
    cout<<solve(a,b,10)%10<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42868863/article/details/113830643