1. 程式人生 > >HDU 4704 Sum 費馬小定理+快速冪

HDU 4704 Sum 費馬小定理+快速冪

Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 18    Accepted Submission(s): 9


Problem Description

Sample Input 2
Sample Output 2 Hint 1. For N = 2, S(1) = S(2) = 1. 2. The input file consists of multiple test cases.
Source
Recommend zhuyuanchen520 題意: 略 思路: 求 2 ^(n - 1) % mod = ? 由費馬小定理得, 2 ^ (n - 1) % p = 2 ^ [(n - 1) % (p - 1)] % p
#include <iostream>
#include<stdio.h>
#include<string.h>
#define MOD 1000000007
using namespace std;

char s[10000005];

__int64 fun(char *s,int m)
{
    __int64 ret=0,e=1;
    for(int i=strlen(s)-1;i>=0;i--)
        {
            ret=((s[i]-'0')*e+ret)%m;
            e=e*10%m;
        }
    return ret;
}

__int64 pow_mod(__int64 a,__int64 n,__int64 m)
{
    if(n==1) return(a%m);
    __int64 x=pow_mod(a,n/2,m);
    __int64 ans=x*x%m;
    if(n%2==1) ans=ans*a%m;
    return ans;
}



int main()
{
    __int64 a,b,ans;
    int i;
    while(~scanf("%s",s))
    {
        int t,len=strlen(s);
        t=len-1;
        while(s[t]=='0')
        {
            s[t]='9';
            t--;
        }
        s[t]=s[t]-1;

        //printf("*%s\n",s);
        b=fun(s,MOD-1);
        //printf("%I64d\n",b);
        if(b==0) printf("1\n");
        else printf("%I64d\n",pow_mod(2,b,MOD));
    }

    return 0;
}
快速冪的寫法: __int64 Quick_Pow(__int64 a, __int64 b) {
    __int64 res = 1;
    while(b) {
        if(b & 1)
            res = (res * a) % mod;
        b /= 2;
        a = (a * a) % mod;
    }
    return res % mod;
}