2019计蒜之道初赛第3场-阿里巴巴协助征战SARS 费马小定理降幂

题目链接:https://nanti.jisuanke.com/t/38352

发现规律之后就是算ans=2^(n-1)+4^(n-1)。但是注意到n十分大是一个长度为1e5的数字。要想办法降幂。

我们观察费马小定理:a^(p-1)%p=1。发现对于质数取模,a^(p-1)是一个循环节(因为算出来等于1),可以忽略掉不算。

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
const int P=1e9+7;
typedef long long LL;
char s[N];

LL power(LL x,LL p) {
    LL ret=1;
    for (;p;p>>=1) {
        if (p&1) ret=(ret*x)%P;
        x=(x*x)%P;
    }
    return ret;
}

int main()
{
    while (scanf("%s",s) && s[0]!='0') {
        LL n=0;
        for (int i=0;i<strlen(s);i++) {
            n=n*10%(P-1)+(s[i]-'0'); n%=(P-1);
        }
        n=((n-1)+(P-1))%(P-1);
        printf("%d\n",(power(2,n)+power(4,n))%P);
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/clno1/p/10987740.html