Computing nCr without overflow
1 Choosing r out of n
A teacher picks 2 of 4 students, A, B, C and D, to carry the books. The order does not matter: A with B is the same pair as B with A. Listing every pair gives six:
AB AC AD BC BD CD
This count is nCr, written C(n, r). It is the number of ways to choose r things out of n when the order does not matter. Here C(4, 2) = 6. The usual formula uses factorials:
For our example, that is 24 ÷ (2 × 2) = 6. In code, the formula breaks early, because factorials grow faster than any integer type:
| n | n! | Fits in |
|---|---|---|
| 12 | 479,001,600 | 32 bits (up to about 2.1 × 10⁹) |
| 13 | about 6.2 × 10⁹ | 64 bits only |
| 20 | about 2.4 × 10¹⁸ | 64 bits (up to about 9.2 × 10¹⁸) |
| 21 | about 5.1 × 10¹⁹ | neither |
The answer is often small. C(21, 10) is just 352,716, but the formula first calculates 21!. That overflows, and the division then works on a wrong number. So we need ways that never build a big factorial. There are three, and each suits a different kind of problem.
2 Pascal's triangle: add the two above
Go back to the four students and look at D. Every pair either has D in it or does not:
- Pairs with D. The other place goes to one of A, B and C. That is C(3, 1) = 3 pairs: AD, BD and CD.
- Pairs without D. Both places go to A, B and C. That is C(3, 2) = 3 pairs: AB, AC and BC.
So C(4, 2) = 3 + 3 = 6. The same split works for any n and r, because the last item is either chosen or not:
Writing the values row by row gives Pascal's triangle. Row n holds C(n, 0) to C(n, n), counting from 0. The edges are all 1: there is one way to choose nothing, and one way to choose everything. Every other number is the sum of the two above it.
3 Building the whole table
Each row needs only the row above, so we build the rows from the top down. Every step is an addition, and every number is an answer, so nothing grows past the largest answer.
The answers themselves still pass 64 bits from row 67: C(67, 33) is about 1.4 × 10¹⁹. So a bigger table keeps each value modulo a prime, usually 10⁹ + 7. Two values below 10⁹ + 7 add up to about 2 × 10⁹, and taking the remainder after each addition keeps every value small.
Row n has n + 1 values, so the table takes O(n²) time and space. For n = 1,000 that is about 5 × 10⁵ values, which is quick. For n = 10⁵ it is about 5 × 10⁹, far past the time limit. The table suits problems that need many values, with n up to a few thousand.
4 One value: walk along the row
For one value with a large n, we walk along row n from C(n, 0) = 1 instead. Each step to the right uses one rule:
The rule comes from the formula. C(n, i) is n × (n − 1) × … × (n − i + 1) on top, over 1 × 2 × … × i. One step right adds one factor on top, n − i, and one on the bottom, i + 1.
A row also reads the same from both ends. Choosing r students to take is the same as choosing n − r to leave, so C(n, r) = C(n, n − r). We walk only min(r, n − r) steps. For C(8, 5), that is 3 steps:
i | value | × (n − i) | product | ÷ (i + 1) | new value |
|---|---|---|---|---|---|
| 0 | 1 | × 8 | 8 | ÷ 1 | 8 |
| 1 | 8 | × 7 | 56 | ÷ 2 | 28 |
| 2 | 28 | × 6 | 168 | ÷ 3 | 56 |
Every division here is exact. After step i, value is C(n, i + 1), a count of choices, so it is a whole number. The order inside a step matters, though. In the GCD lesson we divided first, because a ÷ gcd(a, b) is always exact. Here value ÷ (i + 1) is not, and integer division drops the remainder:
divide first: 28 / 3 * 6 = 9 * 6 = 54 wrong
multiply first: 28 * 6 / 3 = 168 / 3 = 56 right
C++
Use //. Integers never overflow, so this loop is exact at any size. / would give a float and lose the last digits.
Exact only up to 2⁵³. Each division is exact, so / gives whole numbers. But numbers above about 9 × 10¹⁵ lose their last digits: C(61, 30) comes out ending in 560 instead of 544. Larger answers need BigInt.
The walk is O(min(r, n − r)) time and O(1) space.
5 Huge n: divide by multiplying
C(10⁵, 5 × 10⁴) has about 30,000 digits. No integer type holds it, so problems ask for the answer modulo a prime p, usually 10⁹ + 7. The previous lesson showed that addition and multiplication work under a modulo: we take the remainder after every step. Division does not.
With p = 7, C(4, 2) = 24 ÷ 4 = 6. But 24 mod 7 is 3, and 3 ÷ 4 is not a whole number.
Instead, we multiply by an inverse. The inverse of 4 modulo 7 is the number x with 4 × x mod 7 = 1. It is 2, because 4 × 2 = 8 = 7 + 1. Multiplying by 2 now does the work of dividing by 4: 3 × 2 = 6, the right answer.
When p is prime, Fermat's little theorem gives the inverse. For any a that p does not divide, ap−1 mod p = 1. Splitting off one a gives a × ap−2 mod p = 1, so ap−2 is the inverse of a. For 4 modulo 7, 4⁵ = 1,024, and 1,024 mod 7 = 2. Fast power from the previous lesson calculates it in about 30 rounds of its loop for p = 10⁹ + 7.
So each division by a factorial becomes a multiplication by its inverse:
6 Factorials and their inverses, once
Problems often ask for many values. So we calculate two arrays once, up to the largest n, N: fact[i] is i! mod p, and invFact[i] is its inverse.
factfills upwards. fact[0] = 1, and fact[i] = fact[i − 1] × i mod p.invFactfills downwards. One fast power gives invFact[N] = fact[N]p−2. After that, invFact[i − 1] = invFact[i] × i, because 1 ÷ (i − 1)! = i ÷ i!.
So the whole of invFact costs one fast power and N multiplications. Here it is with p = 7 and N = 6, small enough to check by hand:
Each fact[i] × invFact[i] comes to 1 modulo 7, as an inverse should: fact[4] × invFact[4] = 3 × 5 = 15, and 15 mod 7 = 1. Now one value takes three multiplications. C(6, 2) = 15, and 15 mod 7 = 1. From the arrays, fact[6] × invFact[2] × invFact[4] = 6 × 4 × 5 = 120, and 120 mod 7 = 1 too.
C++
64-bit products. Every value stays below 10⁹ + 7, but two of them multiply to about 10¹⁸. That needs long long, even though each value fits in an int.
64-bit products. Every value stays below 10⁹ + 7, but two of them multiply to about 10¹⁸. That needs long, even though each value fits in an int.
pow(a, b, p) is fast power. With three arguments, the built-in pow works modulo p, so we need no helper.
BigInt throughout. Two values below 10⁹ + 7 multiply to about 10¹⁸, well past 2⁵³, where numbers stop being exact.
64-bit products. Every value stays below 10⁹ + 7, but two of them multiply to about 10¹⁸. That needs int64, even though each value fits in an int32.
64-bit products. Every value stays below 10⁹ + 7, but two of them multiply to about 10¹⁸. That needs i64, even though each value fits in an i32.
64-bit products. Every value stays below 10⁹ + 7, but two of them multiply to about 10¹⁸. That needs long, even though each value fits in an int.
Filling both arrays takes O(N) time and O(N) space, plus one fast power of O(log p). After that, each value is O(1). For N = 10⁶, that is about 10⁶ steps, once.
7 Mistakes and edge cases
- Walking past the middle. C(100, 98) is only 4,950. A walk to column 98 passes C(100, 50), about 10²⁹, on the way. Walking min(98, 2) = 2 steps stays small.
- The product overflows near the limit. Before each division, the product is i + 1 times the new value. C(62, 31) is about 4.7 × 10¹⁷ and fits, but its last product, C(62, 30) × 32, is about 1.4 × 10¹⁹ and does not. Cancelling the GCD of
valueand i + 1 before multiplying fixes it, and one of the practice problems needs that. - Taking the remainder only at the end.
fact[i]passes 64 bits at i = 21. The remainder must come after every multiplication, not once at the end. - r outside 0 to n. There is no way to choose 7 out of 5, so C(5, 7) = 0. Without the check, the code reads
invFact[−2], a Runtime Error. C(n, 0) and C(n, n) are both 1. - n at least p. Fermat needs p not to divide n!. With p = 10⁹ + 7 and n up to 10⁶, it never does. With p = 7 and n = 7, fact[7] mod 7 is 0, and 0 has no inverse.
8 Which way to use
| Way | Time | Space | Best for |
|---|---|---|---|
| Pascal's table | O(n²) once | O(n²) | many values, n up to a few thousand |
| Walk along the row | O(min(r, n − r)) per value | O(1) | one exact value that fits in 64 bits |
| Factorials and inverses | O(N) once, O(1) per value | O(N) | values modulo a prime, n up to about 10⁶ |
A problem needs this lesson when it counts ways to choose, or asks for rows of Pascal's triangle:
- "Return row k", or "the first k rows". Build the rows with the addition rule.
- One exact value, with a huge n. Walk along the row for min(r, n − r) steps.
- "Return the count modulo 10⁹ + 7". Precompute the factorials and their inverses.
The habit to keep: check the largest number a formula builds on the way, not just the answer. The overflow hides in the factorials and in the product before each division.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.