Binomial Queries

easy combinatorics number-theory math prefix-sums 1000 ms · 256 MB

Binomial Queries

You are given q queries. Each query gives two integers n and k, and asks for the number of ways to choose k items out of n distinct items, taken modulo 1 000 000 007.

Formally, for each query output C(n, k) mod (10^9 + 7), where C(n, k) = n! / (k! · (n-k)!) is the binomial coefficient. If k > n, there is no way to choose, so the answer is 0. If k = 0 or k = n, the answer is 1.

Input

The first line contains a single integer q (1 ≤ q ≤ 10^5), the number of queries.

Each of the next q lines contains two integers n and k (0 ≤ k ≤ 10^6, 0 ≤ n ≤ 10^6) describing one query. k may exceed n.

Output

Print q lines. The i-th line must contain C(n_i, k_i) mod (10^9 + 7) for the i-th query.

Notes

In the first example, C(5, 2) = 10, C(5, 0) = 1, and C(3, 5) = 0 since you cannot choose 5 items out of only 3.

With n reaching 10^6 and q reaching 10^5, building a fresh Pascal's triangle per query, or recomputing factorials from scratch each time, is too slow — the intended solution answers every query in O(1) after a single O(n_max) precomputation.

Example 1

Input

3
5 2
5 0
3 5

Output

10
1
0

Example 2

Input

4
10 3
0 0
1000000 1
7 7

Output

120
1
1000000
1

Hints · reveal one at a time if you're stuck

Hint 1

Working out each binomial coefficient from scratch for every query is too slow with n up to 10^6 and 10^5 queries. What can be computed once in advance and reused, and what does the modulus being prime let you do with division?

Hint 2

Precompute factorials modulo 10^9+7 up to the largest n, and their inverses by applying Fermat's little theorem once to the largest factorial, then working downward. A query then reduces to a few multiplications, but first handle the case where k is larger than n.

report an issue Prefer your own editor? sooks prep 55 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.