HDU 4704 Sum (费马小定理)

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=4704


题意:



不知道为什么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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值