典型的卡特兰数问题,答案就是卡特兰数列前n项和。
关于卡特兰数列:
http://www.cppblog.com/MiYu/archive/2010/08/07/122573.html
这里比较棘手的问题就是取模问题,要用到乘法逆元,但比起HDOJ4828这道题来
(http://blog.csdn.net/moringrain/article/details/47341247)
比较难处理的是模是一个不确定的数,并不能保证与分母(i+1)互质。
所以我们要把m的质因数分解出来,然后从分母中剔除这些质因数,同时也剔除分子中的这些数,使总的大小不变。
但是(4i-2)/(i+1)不一定能整除,如果先计算(4i-2)*h[i-1]的话还会先爆longlong(这时候还不能取模)。
所以我们可以先开一个数组来记录分子分母中m包含的各个质因数的个数,分子中出现一次+1,分母中出现一次-1。
计算出逆元、相乘后别忘记把质数表里的数乘起来。
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef long long LL;
//计算 ax+by=gcd(a,b),返回gcd值,求出xy
LL Ex_gcd(LL a, LL b, LL &x, LL &y)
{
LL d;
if (a == 0 && b == 0) return -1;// 无GCD
if (b == 0)
{
x = 1;
y = 0;
return a;
}
d = Ex_gcd(b, a%b, y, x);
y -= a / b * x;
return d;
}
//求a关于模n的逆元,不存在返回-1
LL Mod_reverse(LL a, LL n)
{
LL x, y, d;
d = Ex_gcd(a, n, x, y);
if (d == 1)
return (x % n + n) % n;
else
return -1;
}
void work(int n, LL m)
{
LL PrimeNumber[10000];
LL NumberCount[10000];
LL i, t, ans, temp, den, inv, ctl;
int j, k, cnt;
if (m == 1)
{
puts("0");
return;
}
memset(PrimeNumber, 0, sizeof(PrimeNumber));
memset(NumberCount, 0, sizeof(NumberCount));
cnt = 0;
t = m;
for (i = 2; i*i < m; i++)
{
if (t % i == 0)
{
PrimeNumber[cnt++] = i;
while (t % i == 0)
t /= i;
}
}
if (t > 1)
PrimeNumber[cnt++] = t;
ans = 1;
ctl = 1;
for (i = 2; i <= n; i++)
{
temp = 4 * i - 2;
for (j = 0; j < cnt; j++)
while (temp % PrimeNumber[j] == 0)
{
temp /= PrimeNumber[j];
NumberCount[j]++;
}
ctl = (ctl*temp) % m;
temp = i + 1;
for (j = 0; j < cnt; j++)
while (temp % PrimeNumber[j] == 0)
{
temp /= PrimeNumber[j];
NumberCount[j]--;
}
inv = Mod_reverse(temp, m);
ctl = (ctl * inv) % m;
temp = ctl;
for (j = 0; j < cnt; j++)
for (k = 1; k <= NumberCount[j]; k++)
temp = (temp * PrimeNumber[j]) % m;
ans = (ans + temp) % m;
}
printf("%I64d\n", ans);
}
int main()
{
int n;
LL m;
while (scanf("%d%I64d", &n, &m),n+m)
work(n, m);
return 0;
}