您的位置:首页 > 其它

卢卡斯定理的模板以及应用

2016-08-04 19:17 218 查看
定义:

Lucas定理是用来求 C(n,m)C(n,m) MODMOD pp,p为素数的值。Lucas定理:我们令n=sp+q,m=tp+r.(q,r≤p)n=sp+q , m=tp+r .(q ,r ≤p)

那么:(在编程时你只要继续对 调用 LucasLucas 定理即可。代码可以递归的去完成这个过程,其中递归终点为 t=0t = 0 ;时间复杂度 O(logp(n)∗p):)O(log_p(n)*p):)

主要解决当 n,mn, m 比较大的时候,而 pp 比较小的时候 <1e6<1e6 ,那么我们就可以借助 卢卡斯定理来解决这个问题:

模板:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int INF = 1e9+5;
const int MAXN = 1e6+5;
const int MOD = 1e9+7;
const double eps = 1e-7;
const double PI = acos(-1);
using namespace std;
LL quick_mod(LL a, LL b, LL c)
{
LL ans = 1;
while(b)
{
if(b & 1)
ans = (ans*a)%c;
b>>=1;
a = (a*a)%c;
}
return ans;
}
LL fac[MAXN];
void Get_Fac(LL m)///m!
{
fac[0] = 1;
for(int i=1; i<=m; i++)
fac[i] = (fac[i-1]*i) % m;
}
LL Lucas(LL n, LL m, LL p)
{
LL ans = 1;
while(n && m)
{
LL a = n % p;
LL b = m % p;
if(a < b)
return 0;
ans = ( (ans*fac[a]%p) * (quick_mod(fac[b]*fac[a-b]%p,p-2,p)) ) % p;
n /= p;
m /= p;
}
return ans;
}
int main()
{
LL n, m, p;
Get_Fac(p);
Lucas(n, m, p);///C(n,m)%p
return 0;
}


应用:

HDU 3037

题目大意:

求 C(n+m,m)C(n+m,m) % PP

AC代码:AC代码:

/**
2016 - 08 - 04 晚上
Author: ITAK

Motto:

今日的我要超越昨日的我,明日的我要胜过今日的我,
以创作出更好的代码为目标,不断地超越自己。
**/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int INF = 1e9+5;
const int MAXN = 1e6+5;
const int MOD = 1e9+7;
const double eps = 1e-7;
const double PI = acos(-1);
using namespace std;
LL quick_mod(LL a, LL b, LL c)
{
LL ans = 1;
while(b)
{
if(b & 1)
ans = (ans*a)%c;
b>>=1;
a = (a*a)%c;
}
return ans;
}
LL fac[MAXN];
void Get_Fact(LL m)///m!
{
fac[0] = 1;
for(int i=1; i<=m; i++)
fac[i] = (fac[i-1]*i) % m;
}
LL Lucas(LL n, LL m, LL p)
{
LL ans = 1;
while(n && m)
{
LL a = n % p;
LL b = m % p;
if(a < b)
return 0;
ans = ( (ans*fac[a]%p) * (quick_mod(fac[b]*fac[a-b]%p,p-2,p)) ) % p;
n /= p;
m /= p;
}
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
LL n, m, p;
scanf("%I64d%I64d%I64d",&n,&m,&p);
Get_Fact(p);
printf("%I64d\n",Lucas(n+m,m,p));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: