HDU4704:Sum(欧拉降幂公式)

Input

2

Output

2

Sample Input

2

由公式,ans=2^(N-1)%Mod=2^((N-1)%(Mod-1)+(Mod-1)) %Mod。

注意:降幂的之后再加一个Mod-1保险,避免为负,比如此题出入1000000006时,就出问题了。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
const int Mod=1e9+7;
char c[100010];
ll ans,sum,g;
ll qpow(ll a,ll x){
    ll res=1;
    while(x){
        if(x&1) res=res*a%Mod;
        x>>=1;
        a=a*a%Mod;
    }
    return res;
}
int main()
{
    int L,i,j;
    while(~scanf("%s",c+1)){
        L=strlen(c+1);
        sum=0;g=1;
        for(i=L;i>=1;i--){
            sum=(sum+(c[i]-'0')*g)%(Mod-1);
            g=g*10%(Mod-1);
        }
        ans=qpow(2,sum+Mod-2);
        printf("%lld
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/hua-dong/p/8604489.html