盧卡斯定理的模板以及應用
阿新 • • 發佈:2019-02-03
定義:
Lucas定理是用來求
那麼:(在程式設計時你只要繼續對 呼叫
主要解決當
模板:
#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
題目大意:
求
/**
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;
}