普通递推的方法不能用来取模,因为(4*n-2)/(n+1)可能是小数。
可以利用另外一个公式:(2*n)!/n!*(n+1)!
可以利用素数的幂来求阶乘,然后就可以在计算的过程中取模。
http://suo.im/cj3mc
#include
#include
#include
#include
using namespace std;
typedef long long ll;
int dp[1000005];
bool isprime[1000005];
ll prime[200005], top;
void Prime(int n)
{
top = 0;
memset(isprime, true, sizeof(isprime));
for(int i = 2; i < n; i++){
if(isprime[i])
prime[top++] = i;
for(int k = 0; k < top && i * prime[k] < n; k++){
isprime[i*prime[k]] = false;
if(i % prime[k] == 0)
break;
}
}
}
ll quickpow(ll m, ll n, ll mod)
{
ll b = 1;
while(n){
if (n & 1)
b = (b * m) % mod;
n = n >> 1 ;
m = (m * m) % mod;
}
return b;
}
void fac_1(ll n)
{
ll len = -1;
while(prime[++len] <= n){
ll sum = 0;
dp[prime[len]] = 0;
ll num = prime[len];
while(num <= n){
sum += n / num;
num = num * prime[len];
}
dp[prime[len]] += sum;
}
}
void fac_2(ll n)
{
ll len = -1;
while(prime[++len] <= n){
ll sum = 0;
ll num = prime[len];
while(num <= n){
sum += n / num;
num = num * prime[len];
}
dp[prime[len]] -= sum;
}
}
int main()
{
ll n, m;
Prime(1000000);
while(cin>>n>>m){
n = n - 2;
if(m == 1){
cout<<"0"<continue;
}
if(n == 1){
cout<<"1"<continue;
}
fac_1(2 * n);
fac_2(n);
fac_2(n+1);
int resl = 1;
for(int i = 0; prime[i] <= 2*n; i++){
if(dp[prime[i]])
resl = (resl * quickpow(prime[i], dp[prime[i]], m)) % m;
}
cout<return 0;
}