本来想做NEU_OJ的1305的,可是发现自己始终AC不了,看了半天的lucas算法,公式肯定能记住,但是不是很理解。
所以只能把大佬的代码贴上来了。
转载自:https://blog.csdn.net/acdreamers/article/details/8037918
题目来源:http://acm.fzu.edu.cn/problem.php?pid=2020
代码:
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; typedef long long LL; LL n,m,p; 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; //必须要保证m <= n 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) { if(m == 0) return 1; return C(n % p, m % p) * Lucas(n / p, m / p) % p; } int main() { int T; scanf("%d", &T); while(T--) { scanf("%I64d%I64d%I64d", &n, &m, &p); printf("%I64d\n", Lucas(n,m)); } return 0; }