All problems

Problem 554

Binomial Coefficient Modulo a Small Prime

Hard · 30 pts · Math, Number Theory, Combinatorics

Problem

Compute C(N, R) modulo a prime P, where N and R can be as large as 10^18 but P is small. Factorials cannot be stored for such N, so use Lucas's theorem: write N and R in base P, and C(N, R) mod P equals the product of C(n_i, r_i) mod P over the base-P digits, with C(n_i, r_i) = 0 whenever r_i > n_i. Each small binomial needs only factorials below P. If R > N the answer is 0. The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).

Input

A single line with three integers N, R and P.

Output

Print C(N, R) modulo P.

Constraints

0 <= N, R <= 10^18; 2 <= P <= 1000; P is prime

Example input

10 3 13

Example output

3

Explanation

C(10, 3) = 120, and 120 = 9 × 13 + 3, so modulo 13 the answer is 3. Lucas's theorem gives the same: 10 and 3 are single base-13 digits, and C(10, 3) mod 13 = 3.

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

Previous: Count Derangements Next: Trailing Zeros of N! in Base B