逻辑差不多的两份代码,第一份是预处理各阶乘的逆元,第二份是将求逆元的操作放进组合数里,可是为什么第一份代码 WA 了两点,蒟蒻没找到原因(
第一份代码:
#include<iostream>
#define int long long
using namespace std;
int fact[100007], infact[100007];
int pow(int x, int k, int p)
{
int res = 1;
while (k)
{
if(k & 1) res = res * x % p;
x = x * x % p;
k >>= 1;
}
return res;
}
int C(int a, int b, int p)
{
if(b > a) return 0;
return fact[a] * infact[a - b] % p * infact[b] % p;
}
int Lucas(int a, int b, int p)
{
if(!b) return 1;
return C(a % p, b % p, p) * Lucas(a / p, b / p, p) % p;
}
signed main()
{
int t;
cin >> t;
while (t -- )
{
int a, b, p;
cin >> a >> b >> p;
fact[0] = 1;
for(int i = 1; i <= p; i ++ )
{
fact[i] = fact[i - 1] * i % p;
infact[i] = pow(fact[i], p - 2, p);
}
cout << Lucas(a + b, b, p) << endl;
}
return 0;
}
第二份代码:
#include<iostream>
#define int long long
using namespace std;
int fact[100007], infact[100007];
int pow(int x, int k, int p)
{
int res = 1;
while (k)
{
if(k & 1) res = res * x % p;
x = x * x % p;
k >>= 1;
}
return res;
}
int C(int a, int b, int p)
{
if(b > a) return 0;
return fact[a] * pow(fact[b], p - 2, p) % p * pow(fact[a - b], p - 2, p) % p;
}
int Lucas(int a, int b, int p)
{
if(!b) return 1;
return C(a % p, b % p, p) * Lucas(a / p, b / p, p) % p;
}
signed main()
{
int t;
cin >> t;
while (t -- )
{
int a, b, p;
cin >> a >> b >> p;
fact[0] = 1;
for(int i = 1; i <= p; i ++ )
{
fact[i] = fact[i - 1] * i % p;
infact[i] = 0;
// cout << fact[i] << ' ' << infact[i] << endl;
}
cout << Lucas(a + b, b, p) << endl;
}
return 0;
}
评测记录: