肯定是尽量走1,因为最左边的1和最右边的1相同,所以我们考虑一边就行了,就考虑(m < k/2)
最后我们推出来的公式为:
C(n+1,m)+(n-m)
因为C(n+1,m)很大。
要用到Lucas定理
什么是Lusac(卢卡斯)定理?
Lucas定理是用来求 c(n,m) mod p,p为素数的值。
对于C(n, m) mod p。这里的n,m,p(p为素数)都很大的情况。就不能再用C(n, m) = C(n - 1,m) + C(n - 1, m - 1)的公式递推了。
参考http://www.cnblogs.com/vongang/archive/2012/12/02/2798138.html
For non-negative integers m and n and a prime p, the following congruence relation holds:
where
and
are the base p expansions of m and n respectively.
对于单独的C(ni, mi) mod p,已知C(n, m) mod p = n!/(m!(n - m)!) mod p。显然除法取模,这里要用到m!(n-m)!的逆元。
根据费马小定理:
http://blog.csdn.net/ac__y/article/details/9248023
已知(a, p) = 1,则 ap-1 ≡ 1 (mod p), 所以 a*ap-2 ≡ 1 (mod p)。
也就是 (m!(n-m)!)的逆元为 (m!(n-m)!)p-2 ;
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define LL long long
LL ni(LL b,LL n,LL p)
{
LL x=1;
while(n)
{
if(n&1) x=(x*b)%p;
b=(b*b)%p;
n>>=1;
}
return x;
}
LL c(LL n,LL m,LL p)
{
if(m>n) return 0;
else if(n==m) return 1;
if(m>n/2) m=n-m;
LL a=1,b=1;
for(int i=0;i<m;i++)
{
a=(a*(n-i))%p;
b=(b*(i+1))%p;
}
return (a*ni(b,p-2,p))%p;
}
LL Lucas(LL n,LL m,LL p)
{
LL ans=1;
while(n&&m&&p)
{
ans=(ans*c(n%p,m%p,p))%p;
n=n/p;
m=m/p;
}
return ans;
}
int main()
{
LL n,m,p;
int case1=1;
while(scanf("%I64d %I64d %I64d",&n,&m,&p)!=EOF)
{
if(m>n/2) m=n-m;
printf("Case #%d: %I64d\n",case1++,((n-m)+Lucas(n+1,m,p))%p);
}
return 0;
}