Skip to content
BytePatterns

Choose K Modulo A Prime

MediumMath & Number Theory#combinatorics#modular-inverse~30m

Problem

Count the ways to pick k items out of n distinct items when the order of picking does not matter, and report the count modulo 1,000,000,007, which is prime. The value of n can reach a million, so the exact count has hundreds of thousands of digits and must never be built. Picking more items than exist gives zero ways.

Examples

Input:  n = 5, k = 2
Output: 10
Input:  n = 1000, k = 500
Output: 159835829
Why:    the exact count has about 300 digits; only its remainder is returned
Input:  n = 3, k = 5
Output: 0
Why:    edge case, there is no way to pick five items out of three

Hints

0 / 3

Stuck on the idea rather than the code? Permutations vs Combinations covers it.