Unknown Treasure
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 3047 Accepted Submission(s): 1122
Problem Description
On the way to the next secret treasure hiding place, the mathematician discovered a cave unknown to the map. The mathematician entered the cave because it is there. Somewhere deep in the cave, she found a treasure chest with a combination lock and some numbers on it. After quite a research, the mathematician found out that the correct combination to the lock would be obtained by calculating how many ways are there to pick
m
different apples among
n
of them and modulo it with
M
.
M
is the product of several different primes.
Input
On the first line there is an integer
T(T≤20)
representing the number of test cases.
Each test case starts with three integers n,m,k(1≤m≤n≤1018,1≤k≤10) on a line where k is the number of primes. Following on the next line are k different primes p1,...,pk . It is guaranteed that M=p1⋅p2⋅⋅⋅pk≤1018 and pi≤105 for every i∈{1,...,k} .
Each test case starts with three integers n,m,k(1≤m≤n≤1018,1≤k≤10) on a line where k is the number of primes. Following on the next line are k different primes p1,...,pk . It is guaranteed that M=p1⋅p2⋅⋅⋅pk≤1018 and pi≤105 for every i∈{1,...,k} .
Output
For each test case output the correct combination on a line.
Sample Input
1 9 5 2 3 5
Sample Output
6
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define LL long long
LL n,m,p;
LL k;
LL a[15];
LL m1[15];
LL quick_mod(LL a, LL b)
{
LL ans = 1;
a %= p;
while(b)
{
if(b & 1)
{
ans = ans * a % p;
b--;
}
b >>= 1;
a = a * a % p;
}
return ans;
}
LL C(LL n, LL m)
{
if(m > n) return 0;
LL ans = 1;
for(int i=1; i<=m; i++)
{
LL a = (n + i - m) % p;
LL b = i % p;
ans = ans * (a * quick_mod(b, p-2) % p) % p;
}
return ans;
}
LL Lucas(LL n, LL m) //计算C(n,m)%p,且p一定为素数
{
if(m == 0) return 1;
return C(n % p, m % p) * Lucas(n / p, m / p) % p;
}
LL extgcd(LL a,LL b,LL&x,LL&y) //扩展欧几里德返回gcd(a,b)
{
LL d=a;
if(b!=0)
{
d=extgcd(b,a%b,y,x);
y-=(a/b)*x;
}
else
{
x=1;
y=0;
}
return d;
}
LL mul(LL a, LL b, LL mod) {
a = (a % mod + mod) % mod;
b = (b % mod + mod) % mod;
LL ret = 0;
while(b){
if(b&1){
ret += a;
if(ret >= mod) ret -= mod;
}
b >>= 1;
a <<= 1;
if(a >= mod) a -= mod;
}
return ret;
}
LL china(int n, LL* a, LL* m) {
LL M = 1, d, y, x = 0;
for (int i = 0; i < n; i++) M *= m[i];
for (int i = 0; i < n; i++) {
LL w = M / m[i];
extgcd(m[i], w, d, y);
x = (x + mul(mul(y, w, M), a[i], M));
}
return (x + M) % M;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld%d",&n,&m,&k);
for(int i=0;i<k;i++)
{
scanf("%lld",&m1[i]);
}
for(int i=0;i<k;i++)
{
p=m1[i];
a[i]=Lucas(n,m);
}
printf("%lld\n",china(k,a,m1));
}
}