fzu1759:数论高次幂降幂

题目大意:

求 a^b mod c的值。。但是b会非常大(10^1000000)

所以需要用到一个数论公式:

 A^x = A^(x % Phi(C) + Phi(C)) (mod C)

证明见ac大神博客http://hi.baidu.com/aekdycoin/item/e493adc9a7c0870bad092fd9

#include <iostream>
#include <stdio.h>
#include<string.h>
#include<algorithm>
#include<string>
#include<ctype.h>
using namespace std;
#define MAXN 10000
long long a,b,c;
char s[1000010];
long long phi(long long n)
{
    long long res=n;
    for(int i=2; i*i<=n; i++)
    {
        if(n%i==0)
        {
            res=res-res/i;
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1)
        res=res-res/n;
    return res;
}
long long quickmod(long long a,long long b,long long m)
{
    long long res=1;
    while(b)
    {
        if(b&1)
        {
            res=res*a%m;
        }
        a=a*a%m;
        b/=2;
    }
    return res;
}
int main()
{
    while(cin>>a)
    {
        scanf("%s%I64d",s,&c);
        long long p=phi(c);
        int len=strlen(s);
        b=0;
        if(len<=10)
        {
            for(int i=0;i<len;i++)
            {
                b = b*10 + (s[i]-'0');
            }
            printf("%I64d
",quickmod(a,b<p?b:b%p+p,c));
            continue;
        }
        for(int i=0; i<len; i++)
        {
            b=(b*10+(s[i]-'0'))%p;
        }
        printf("%I64d
",quickmod(a,b+p,c));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/oneshot/p/4111468.html