There are 5 distinct binary trees of 3 nodes:
Let T(n) be the number of distinct non-empty binary trees of no more than n nodes, your task is to calculate T(n) mod m.
Input
The input contains at most 10 test cases. Each case contains two integers n and m (1 <= n <= 100,000, 1 <= m <= 10 9) on a single line. The input ends with n = m = 0.
Output
For each test case, print T(n) mod m.
Sample Input
3 100
4 10
0 0
Sample Output
8
2
h(i)=h(i-1)*(4i-2)/(i+1)%m
需要求 i+1 关于m的逆元,要求 i+1 和m互质,
所以我们分解 m,4i-2和 i+1 的质因数,把4i-2和i+1和m互质的部分直接相乘,不互质的部分,分子除以分母剩下的因子再相乘。i+1不互质的部分被4i-2消掉了。
扩展欧几里得求逆元模板:
int exgcd(int a,int b,int &x,int &y)
{
int d=a;
if(b!=0)
{
d=exgcd(b,a%b,y,x);
y-=a/b*x;
}
else
{
x=1;
y=0;
}
return d;
}
int inverse(int a,int m)
{
int x,y;
exgcd(a,m,x,y);
return (x%m+m)%m;
}
质因数分解模板(fat数组保存val的所有不同的质因子,下标从 1 开始):
void find_fat(int val){
tot=0;
for(int i=2;i*i<=val;i++)
{
if(val%i==0)
{
fat[++tot]=i;
}
while(val%i==0)
val/=i;
}
if(val>1) fat[++tot]=val;
}
把val与m的所有不互质因子消掉:
int calc(int val,int ok)
{
for(int i=1;i<=tot;i++)
{
while(val%fat[i]==0)
{
if(ok) num[i]++;
else num[i]--;
val/=fat[i];
}
}
return val;
}
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
ll Cat[maxn];
int num[maxn];
int fat[maxn],tot;
void find_fat(int val){
tot=0;
for(int i=2;i*i<=val;i++)
{
if(val%i==0)
{
fat[++tot]=i;
}
while(val%i==0)
val/=i;
}
if(val>1) fat[++tot]=val;
}
int exgcd(int a,int b,int &x,int &y)
{
int d=a;
if(b!=0)
{
d=exgcd(b,a%b,y,x);
y-=a/b*x;
}
else
{
x=1;
y=0;
}
return d;
}
int inverse(int a,int m)
{
int x,y;
exgcd(a,m,x,y);
return (x%m+m)%m;
}
int calc(int val,int ok)
{
for(int i=1;i<=tot;i++)
{
while(val%fat[i]==0)
{
if(ok) num[i]++;
else num[i]--;
val/=fat[i];
}
}
return val;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&&m==0)
break;
memset(num,0,sizeof(num));
find_fat(m);
Cat[1]=1;
ll ans=1;
for(int i=2;i<=n;i++)
{
Cat[i]=Cat[i-1]*calc(4*i-2,1)%m;
Cat[i]=Cat[i]*inverse(calc(i+1,0),m)%m;
ll tmp=Cat[i];
for(int k=1;k<=tot;k++)
{
for(int j=1;j<=num[k];j++)
{
tmp=tmp*fat[k]%m;
}
}
ans=(ans+tmp)%m;
}
printf("%lld\n",ans);
}
return 0;
}
参考:
https://blog.csdn.net/kele52he/article/details/76165190
https://blog.csdn.net/coraline_m/article/details/9942919