首页 > 代码库 > hdu 4704 费马小定理+快速幂

hdu 4704 费马小定理+快速幂

题意就是:做整数拆分,答案是2^(n-1)

由费马小定理可得:2^n % p = 2^[ n % (p-1) ]  % p

当n为超大数时,对其每个数位的数分开来加权计算

当n为整型类型时,用快速幂的方法求解

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>

using namespace std;

const int Mod = 1e9+7;
char str[100050]; 

__int64 Pow(__int64 n)
{
	__int64 ans = 1, tem = 2;
	while(n){
		if(n%2 == 1) ans = ans * tem % Mod;
		n = n / 2;
		tem = tem * tem % Mod;
	}
	return ans;	
}

int main()
{
	__int64 n;
	while(~scanf("%s", &str))
	{
		int len = strlen(str);
		n = 0;
		for(int i = 0; i < len; i ++)
		{
			n = (n*10 + (str[i]-'0')) % (Mod-1);
		}
		n -= 1;
		__int64 ans = Pow(n);
		printf("%I64d\n", ans);
	}
	return 0;
}