1. 问题描述:
给定 n 组询问,每组询问给定两个整数 a,b,请你输出 Cba mod(10 ^ 9 + 7) 的值。
输入格式
第一行包含整数 n。接下来 n 行,每行包含一组 a 和 b。
输出格式
共 n 行,每行输出一个询问的解。
数据范围
1 ≤ n ≤ 10000,
1 ≤ b ≤ a ≤ 10 ^ 5
输入样例:
3
3 1
5 3
2 2
输出样例:
3
10
1
来源:https://www.acwing.com/problem/content/description/888/
2. 思路分析:
因为mod = 10 ^ 9 + 7是一个质数,所以我们根据费马小定理预处理出所有的阶乘以及逆元,a ^ (p - 1) ≡ 1 (mod p),其中a ^ (p - 2)为a关于p的逆元,然后根据Cnm = n! / (m! (n - m)!) 公式计算即可。费马小定理:
- 如果p是一个质数,而整数a不是p的倍数,则有a ^(p - 1)≡ 1(mod p)
3. 代码如下:
from typing import List
class Solution:
def quickPower(self, a: int, b: int, mod: int):
res = 1
while b > 0:
if b & 1:
res = res * a % mod
a = a * a % mod
b >>= 1
return res
def C(self, a: int, b: int, mod: int, fact: List[int], infact: List[int]):
return fact[a] * infact[a - b] * infact[b] % mod
def process(self):
n = int(input())
N, mod = 100010, 10 ** 9 + 7
fact, infact = [0] * N, [0] * N
fact[0] = infact[0] = 1
# 预处理出阶乘以及对应的逆元
for i in range(1, N):
# fact存储阶乘, infact存储阶乘的逆元
fact[i] = fact[i - 1] * i % mod
infact[i] = infact[i - 1] * self.quickPower(i, mod - 2, mod) % mod
for i in range(n):
a, b = map(int, input().split())
print(self.C(a, b, mod, fact, infact))
if __name__ == "__main__":
Solution().process()