题目:http://acm.hdu.edu.cn/showproblem.php?pid=4704
Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1907 Accepted Submission(s): 794
Problem Description
Sample Input
2
Sample Output
2Hint1. For N = 2, S(1) = S(2) = 1. 2. The input file consists of multiple test cases.
因此用到了隔板原理,n个数之间有n-1个间隔,分成1份:一个隔板都不用,C(n-1,0);分成两份:用一个隔板,C(n-1,1);……;分成n份:用去所有的隔板,C(n-1,n-1)。所以结果就应该是[C(n-1,0,)+C(n-1,1)+……+C(n-1,n-1)]%mod. 看见C(n,m)我又想起了杨辉三角,当然这里不能那么干,看见那个N我就打消了原来的念头。。杨辉三角的一行的和(也就是C(n-1,0,)+C(n-1,1)+……+C(n-1,n-1))其实也等于(1+1)^(n-1)=2^(n-1)。这下问题就变成求解2^(n-1)%mod了。由于N太大,必须降幂,费马小定理:假如p是质数,且(a,p)=1,那么 a^(p-1)≡1(mod p)--> a^N%mod=a^(N%(mod-1))%mod。关于大数取模的方法:字符串存储原有的大数,再 ans = (ans * 10 + str[i] - '0')%mod; 因为原值就是在不断减去mod倍。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1e5+10,mod=1e9+7;
char str[maxn];
typedef long long LL;
LL power(int a,int p){
LL ans=1,temp=a;
while(p){
if(p&1) ans=ans*temp%mod;
temp=temp*temp%mod;
p>>=1;
}
return ans;
}
int main()
{
//freopen("cin.txt","r",stdin);
while(cin>>str){
LL p=0,length=strlen(str);
for(int i=0;i<length;i++){
p=(p*10+str[i]-'0')%(mod-1); //2与mod互质,mod是一个素数,可以使用费马小定理
}
p=(p-1+mod-1)%(mod-1);
printf("%lld\n",power(2,p));
}
return 0;
}