Give Candies(费马小定理)
Give Candies
时间限制: 1 Sec 内存限制: 128题目描述
There are N children in kindergarten. Miss Li bought them N candies。To make the process more interesting, Miss Li comes up with the rule: All the children line up according to their student number (1…N), and each time a child is invited, Miss Li randomly gives him some candies (at least one). The process goes on until there is no candy. Miss Li wants to know how many possible different distribution results are there.
输入
The first line contains an integer T, the number of test case.
The next T lines, each contains an integer N.
1 ≤ T ≤ 100
1 ≤ N ≤ 10^100000
The next T lines, each contains an integer N.
1 ≤ T ≤ 100
1 ≤ N ≤ 10^100000
输出
For each test case output the number of possible results (mod 1000000007).
样例输入
1
4
样例输出
8
题意:求2的n次方对1e9+7的模,其中1<=n<=10
100000
。这个就算用快速幂加大数也会超时,查了之后才知道这类题是对费马小定理的考察。
费马小定理:假如p是质数,且gcd(a,p)=1(a,p互质),那么 a^(p-1)≡1(mod p)。
由题可知,1e9+7是个质数(许多结果很大的题都喜欢对1e9+7取模),2是整数,a与p互质显而易见,所以现在我们的目的就是想办法把2^n%(1e9+7)降幂为2^k%(1e9+7),令p=1e9+7,已知a^(p-1) = 1(mod p),且n可能很大很大,就看n里包括多少个p-1,把这些都丢掉求剩下的就好(就是求n mod (p-1),根据取模的性质,这个过程可以将n从第一个数展开过程中边取模完成,详见代码)。假设有x个p-1,则:2^n = 2^(x*(p-1)) * 2^k = 1^x * 2^k = 2^k(mod p),所以直接求2^k就好,k = n%(p-1)。
由于N过于长,就用字符串存储,之后边转化为数边取余。还有就是处理过后的N也不小,求次幂时需要用快速幂。
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<bits/stdc++.h> using namespace std; typedef long long ll; string n; const ll mod=1000000007; ll pow_mod(ll a, ll b){//a的b次方求余p ll ret = 1; while(b){ if(b & 1) ret = (ret * a) % mod; a = (a * a) % mod; b >>= 1; } return ret; } int main(){ int t; scanf("%d",&t); while(t--) { cin>>n; int s1=n.length(); n[s1-1]-=1; for(int i=s1-1; i>=0; i--) { if(n[i]<'0') { n[i]+=10; n[i-1]--; } } //cout<<n<<endl; ll k=(ll)(n[0]-'0'),mod1=mod-1; for(int i=1;i<n.length();i++) k=(k*10+(ll)(n[i]-'0'))%mod1; printf("%lld\n",pow_mod(2,k)); } return 0; }