1. 程式人生 > >2018 ACM/ICPC 焦作賽區網路賽 G 大數取模,費馬小定理

2018 ACM/ICPC 焦作賽區網路賽 G 大數取模,費馬小定理

There are NN children in kindergarten. Miss Li bought them NN 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)(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 TT, the number of test case.

The next TT lines, each contains an integer NN.

1 \le T \le 1001≤T≤100

1 \le N \le 10^{100000}1≤N≤10100000

Output

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

樣例輸入複製

1
4

樣例輸出複製

8

題意:簡單規律題,打個表找到規律,就是求2^(n-1)對1e9+7進行取模。

題解:n很大,有10^100000,所以要用大數取模。

很容易想到費馬小定理。 當p為質數時,2^(p-1)mod p = 1,所以用費馬小定理降冪。

設n-1中有x個(p-1),那麼 2^(n-1) mod p= 2^(x*(p-1)+(n-1)%(p-1)) mod p = 2^((n-1)%(p-1)) mod p 

大數取模求出(n-1)%(p-1) 然後快速冪就行了。


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<vector> 
using namespace std;
#define inf 1e18
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=n;i>=a;i--)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a));
#define lowbit(x)  x&-x;
typedef  long long ll;
const int maxn = 1e5+5;
const int mod = 1e9 + 7;
char s[1005];
ll quick(ll a,ll b){
	ll res = 1;
	while(b){
		if(b&1) res = (res*a)%mod;
		b >>= 1;
		a = (a*a)%mod;
	}
	return res;
}
int main(){
	int t;
	cin>>t;
	
	while(t--){
		scanf("%s",s);
		ll n = s[0] - '0';
		ll MOD = mod - 1;
		int len = strlen(s);
		for(int i = 1; i < len; i++){
			n = (n*10 + s[i]-'0')%MOD;
		}
		n--;
		ll N = quick(2,n);
		printf("%lld\n",N);
	}
}