All problems

Problem 88

Binomial Coefficient Modulo

Medium · 20 pts · Math, Number Theory, Combinatorics

Problem

You are given N and R. Compute C(N, R), the number of ways to choose R items out of N when order does not matter, modulo 1000000007. C(N, R) = N! / (R! × (N - R)!). The factorials are enormous, so work modulo the prime p = 1000000007. Precompute factorials mod p up to N, then divide using modular inverses: by Fermat's little theorem, the inverse of x is x^(p - 2) mod p, computed with fast exponentiation. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).

Input

Two integers N and R.

Output

Print C(N, R) mod 1000000007.

Constraints

0 <= R <= N <= 1000000

Example input

5 2

Example output

10

Explanation

Choosing 2 items out of 5 can be done in C(5, 2) = 5! / (2! × 3!) = 120 / (2 × 6) = 10 ways, and 10 mod 1000000007 = 10.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Excel Column Title Next: Happy Number