2018 ICPC焦作网络赛 G Give Candies(费马小定理+快速幂取模)

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.

Input

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 ≤ 10100000

Output

For each test case output the number of possible results (mod 1000000007).

样例输入

1
4

样例输出

8

题意:

将n个糖果依次分给n个孩子,每次最少分1个糖果,分完即止,请问共有多少种分法。

思路:

通过找打表找规律可知,答案为2n-1,但是n过大,直接计算会超时。

根据费马小定理可知:an%mod = an%(mod-1)%mod【ps:mod为质数】

所以可以推导出公式:2n-1%mod = an%(mod-1)-1%mod

#include<cstdio>
#define MAX 100005
#define mod 1000000007
using namespace std;
typedef long long ll;
char st[MAX];
ll qpm(ll x,ll p)
{
    ll ans=1;
    while(p)
    {
        if(p&1)
            ans=ans*x%mod;
        p>>=1;
        x=x*x%mod;
    }
    return ans; 
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ll p=0;
        int i=0,j;
        scanf("%s",st);
        while(st[i]!='\0')
        {
            p*=10;
            p+=(st[i++]-'0');
            p%=(mod-1);
        }
        p=p-1;
        printf("%lld\n",qpm(2,p));
    }
    return 0;
}

 

posted @ 2018-09-16 11:11  真想不出名字了  阅读(358)  评论(0编辑  收藏  举报