1. 程式人生 > >HDU 4704 Sum (費馬小定理)

HDU 4704 Sum (費馬小定理)

題意:

不知道為什麼java超時:

import java.math.BigInteger;
import java.util.Scanner;


public class Main 
{
	static Scanner cin=new Scanner(System.in);
	public static void main(String[] args)
	{
		BigInteger n,mod1=BigInteger.valueOf(1000000006);
		BigInteger one=BigInteger.ONE;
		int mod2=1000000007;
		while(cin.hasNext())
		{
			n=cin.nextBigInteger();
			n=n.subtract(one);
			n=n.mod(mod1);
			int p=n.intValue();
			int ans=1;
			int a=2;
			while(p!=0)
			{
				if(p%2==1)
					ans=(ans*a)%mod2;
				a=(a*a)%mod2;
				p=p/2;
			}
			System.out.println(ans);
		}

	}

}


C++ AC程式碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
#include <ctime>
using namespace std;

typedef __int64 LL;
const int N=10000005;
const double eps=1e-6;
const int M=100002;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const LL mod1=1000000006;
const LL mod=1000000007;

char s[N];

int main()
{
    while(~scanf("%s",s))
    {
        int len=strlen(s);
        LL p=0;
        for(int i=0;i<len;i++)
        {
            p=(p*10+s[i]-'0')%mod1;
        }
        if(p==0)
            p=mod1-1;
        else
            p--;
        LL ans=1,a=2;
        while(p)
        {
            if(p&1) ans=(ans*a)%mod;
            a=(a*a)%mod;
            p>>=1;
        }
        printf("%I64d\n",ans);
    }
    return 0;
}