快速幂之欧拉降幂

求a^b(mod p)的值 ,当b很大很大很大很大很大的时候,可以使用欧拉降幂

欧拉定理:若n,a为正整数,且n,a互质,则:{{\color{Red} }a^{\phi (n)}\equiv 1(mod n)}

拓展:

那么根据欧拉定理,可以求得φ(n)的值:

ll euler_phi(ll n)
{
    ll k = (ll)sqrt(n + 0.5);
    ll ans = n;
    for(int i = 2; i <= k; 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;
}

看个例题:

求a ^ b mod c  b<=1e1000000000;

#include 
#define ll __int64
using namespace std;

char a[1000006];
ll x, z;
ll quickpow(ll x, ll y, ll z)
{
    ll ans = 1;
    while(y)
    {
        if(y&1)
            ans = ans * x % z;
        x = x * x % z;
        y >>= 1;
    }
    return ans;
}
ll phi(ll n)
{
    ll i, rea = n;
    for(i = 2; i * i <= n; i++)
    {
        if(n % i == 0)
        {
            rea = rea - rea / i;
            while(n % i == 0)
                n /= i;
         }
    }
    if(n > 1)
        rea = rea-rea/n;
    return rea;
}
int main()
{
    while(scanf("%lld %s %lld",&x,a,&z) != EOF)
    {
        ll len = strlen(a);
        ll p = phi(z);
        ll ans = 0;
        for(ll i = 0;i < len; i++)
            ans = (ans*10 + a[i]-'0')%p;
        ans += p;
        printf("%lld\n", quickpow(x, ans, z));
    }
    return 0;
}

 

你可能感兴趣的:(知识点)