1445. Choose Under a Small Prime
A festival committee must pick r volunteers out of n applicants, and the number of possible committees, written C(n, r), is gigantic. The treasurer only needs its remainder when divided by a small prime p, to use as a checksum on the printed forms.
Given n, r and the prime p, return C(n, r) mod p. If r > n, the answer is 0. The values n and r are far too large for factorials, but they have only a few digits in base p: handle the digits pairwise with a factorial table of size p. The intended solution runs in O(p + log_p n) time and O(p) space.
Example 1
- Input:
- n = 10, r = 3, p = 7
- Output:
- 1
- Explanation:
C(10, 3) = 120 and 120 mod 7 = 1; by digits, 10 = (1,3) and 3 = (0,3) in base 7, giving C(1,0) * C(3,3) = 1.
Example 2
- Input:
- n = 6, r = 2, p = 5
- Output:
- 0
- Explanation:
C(6, 2) = 15, and 15 mod 5 = 0; in base 5 the digits give C(1,0) * C(1,2) where 2 > 1, so the product is 0.
Example 3
- Input:
- n = 5, r = 6, p = 3
- Output:
- 0
- Explanation:
You cannot choose 6 out of 5, so r > n gives 0.
Constraints
0 ≤ n, r ≤ 1015
2 ≤ p ≤ 105 and p is prime
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(p + log_p n)
- Space
- O(p)