Skip to lesson

Counting: nCr, Pascal and modular inverse

Many placement problems ask "how many ways" rather than "list every way". Mastering combinations (nCr), Pascal's triangle, and modular division via Fermat's little theorem lets you turn exponential backtracking searches into fast mathematical formulas.

Permutations and Combinations by Formula

When order matters, the number of ways to pick and arrange r items out of n distinct items is a permutation: nPr = n(n-1)…(n-r+1) = (n!)/((n-r)!).

  1. Hand trace of exact C(10, 3): r = min(3, 7) = 3, res = 1.
  2. i = 1: res = 1 * (10 - 3 + 1) / 1 = 8 / 1 = 8 (which is C(8, 1)).
  3. i = 2: res = 8 * (10 - 3 + 2) / 2 = 72 / 2 = 36 (which is C(9, 2)).
  4. i = 3: res = 36 * (10 - 3 + 3) / 3 = 360 / 3 = 120 (which is C(10, 3)).

Example 1 · Brute force: plain recursion with Pascal's identity (exponential time, O(n) stack space)

NcrPlainRecursion.javaJava
public class NcrPlainRecursion {    static long calls = 0;
    public static long nCr(int n, int r) {        calls++;        if (r == 0 || r == n) {            return 1;        }        return nCr(n - 1, r - 1) + nCr(n - 1, r);    }
    public static void main(String[] args) {        System.out.println("C(10, 3) = " + nCr(10, 3) + " using " + calls + " calls");        calls = 0;        System.out.println("C(26, 13) = " + nCr(26, 13) + " using " + calls + " calls");    }}
Output
C(10, 3) = 120 using 239 calls
C(26, 13) = 10400600 using 20801199 calls

What this code does

  • Each call splits into C(n - 1, r - 1) + C(n - 1, r), so the same smaller values are worked out again and again.
  • C(10, 3) needs 239 calls, but C(26, 13) already needs about 20 million. The next examples remove this repeated work.

Example 2 · Optimal for one value: multiply and divide in step (O(r) time, O(1) space)

ExactNcrAndNprDemo.javaJava
public class ExactNcrAndNprDemo {    public static long nPr(int n, int r) {        if (r < 0 || r > n) return 0;        long res = 1;        for (int i = 0; i < r; i++) {            res *= (n - i);        }        return res;    }
    public static long nCrExact(int n, int r) {        if (r < 0 || r > n) return 0;        r = Math.min(r, n - r);        long res = 1;        for (int i = 1; i <= r; i++) {            res = res * (n - r + i) / i;        }        return res;    }
    public static void main(String[] args) {        System.out.println("5P2    = " + nPr(5, 2));        System.out.println("10C3   = " + nCrExact(10, 3));        System.out.println("30C15  = " + nCrExact(30, 15));        System.out.println("50C6   = " + nCrExact(50, 6));    }}
Output
5P2    = 20
10C3   = 120
30C15  = 155117520
50C6   = 15890700

What this code does

  • 30! is 2.65 × 10³² (far past Long.MAX_VALUE), yet nCrExact(30, 15) keeps the intermediate value small by dividing by i at every step.
  • Using r = Math.min(r, n - r) ensures nCrExact(50, 44) does only 6 iterations instead of 44.
  • It is faster than the recursion because each value is built once with r multiplications, with no repeated sub-problems.

When order does not matter, each subset of r items was counted r! times in nPr, so the number of r-element subsets (combinations) is nCr = C(n, r) = (n!)/(r!(n-r)!).

Never compute C(n, r) by evaluating n!, r!, and (n-r)! separately: 21! already overflows a 64-bit long, even though C(30, 15) = 155 117 520 fits in a 32-bit int! Instead, first replace r with min(r, n - r) by symmetry (C(n, r) = C(n, n-r)), then multiply and divide in lockstep for i = 1 … r: res = res * (n - r + i) / i. Because any i consecutive integers contain a multiple of i, the division / i is always exact.

Always write res = res * (n - r + i) / i, NOT res *= (n - r + i) / i! The compound assignment evaluates (n - r + i) / i first with truncated integer division.

Pascal's Triangle for nCr

Every combination C(n, r) satisfies Pascal's identity: C(n, r) = C(n-1, r-1) + C(n-1, r) with base cases C(n, 0) = C(n, n) = 1.

Example 3 · Better for many values: Pascal's triangle table and grid paths (O(n²) time, O(n²) space)

PascalsTriangleDemo.javaJava
import java.util.Arrays;
public class PascalsTriangleDemo {    public static long[][] buildPascal(int maxN) {        long[][] c = new long[maxN + 1][];        for (int i = 0; i <= maxN; i++) {            c[i] = new long[i + 1];            c[i][0] = 1;            c[i][i] = 1;            for (int j = 1; j < i; j++) {                c[i][j] = c[i - 1][j - 1] + c[i - 1][j];            }        }        return c;    }
    public static void main(String[] args) {        long[][] pascal = buildPascal(6);        System.out.println("Row 5: " + Arrays.toString(pascal[5]));        System.out.println("Row 6: " + Arrays.toString(pascal[6]));
        int rows = 3;        int cols = 4;        long gridPaths = pascal[(rows - 1) + (cols - 1)][rows - 1];        System.out.println("Unique paths in 3x4 grid (5C2): " + gridPaths);    }}
Output
Row 5: [1, 5, 10, 10, 5, 1]
Row 6: [1, 6, 15, 20, 15, 6, 1]
Unique paths in 3x4 grid (5C2): 10

What this code does

  • Each interior entry c[i][j] is the sum of the two entries directly above it (c[i - 1][j - 1] + c[i - 1][j]).
  • A 3 × 4 grid requires 2 Down moves and 3 Right moves (5 moves total), so the number of unique paths is C(5, 2) = 10.
  • The table stores every smaller answer once, so each value is an addition instead of a new recursion.

Combinatorially, fix the last item: either you include it (leaving r - 1 items to choose from the remaining n - 1) or you exclude it (leaving all r items to choose from the remaining n - 1).

Building a 2D table C[0..N][0..N] row by row in O(N²) time and space gives O(1) lookup for any C(n, r) with n ≤ N. Because Pascal's recurrence uses only addition, it works under any modulus M — even when M is composite and modular inverses do not exist!

  • Base cases for every row i: C[i][0] = 1 and C[i][i] = 1.
  • Inner transition for 1 ≤ j < i: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % MOD.
  • Ideal when N ≤ 2000 and you need many C(n, r) values.

Precomputed Factorials and Modular Inverse with Fermat's Little Theorem

When N is up to 10⁵ or 10⁶, an O(N²) Pascal table exceeds both time and memory limits. Instead, we use the factorial formula C(n, r) = n! · (r!)⁻¹ · ((n-r)!)⁻¹ mod p, where p = 1 000 000 007 is prime.

Example 4 · nCr Modulo 1e9+7 with Precomputed Factorials and Fermat's Little Theorem

ModNcrFermatDemo.javaJava
public class ModNcrFermatDemo {    public static final long MOD = 1_000_000_007L;    private static final int MAX = 1000;    private static final long[] fact = new long[MAX + 1];
    static {        fact[0] = 1;        for (int i = 1; i <= MAX; i++) {            fact[i] = (fact[i - 1] * i) % MOD;        }    }
    public static long modPow(long base, long exp) {        long res = 1;        base %= MOD;        while (exp > 0) {            if ((exp & 1L) == 1L) res = (res * base) % MOD;            base = (base * base) % MOD;            exp >>= 1;        }        return res;    }
    public static long modInverse(long a) {        return modPow(a, MOD - 2);    }
    public static long nCrMod(int n, int r) {        if (r < 0 || r > n) return 0;        long num = fact[n];        long den = (fact[r] * fact[n - r]) % MOD;        return (num * modInverse(den)) % MOD;    }
    public static void main(String[] args) {        System.out.println("modInverse(3) = " + modInverse(3));        System.out.println("6C2 mod 1e9+7   = " + nCrMod(6, 2));        System.out.println("20C10 mod 1e9+7 = " + nCrMod(20, 10));    }}
Output
modInverse(3) = 333333336
6C2 mod 1e9+7   = 15
20C10 mod 1e9+7 = 184756

What this code does

  • 3 * 333_333_336 = 1_000_000_008, which leaves remainder 1 modulo 1_000_000_007, confirming that 333_333_336 is 3⁻¹ mod 10⁹+7.
  • Multiplying fact[r] and fact[n - r] first and taking a single modInverse(den) requires only one binary exponentiation per nCrMod call.
  • Fermat's Little Theorem requires that the modulus p is prime and a mod p ≠ 0.
  • modInverse(a, p) = modPow(a, p - 2, p) runs in ≈ 30 steps for p = 10⁹ + 7.
  • nCrMod(n, r) = fact[n] * modInverse(fact[r]) % p * modInverse(fact[n - r]) % p.

In modular arithmetic, dividing by a modulo p means multiplying by the modular multiplicative inverse a⁻¹, the unique integer in 1 … p - 1 satisfying (a · a⁻¹) mod p = 1. By Fermat's Little Theorem, whenever p is prime and a ≢ 0 mod p, we have a^(p-1) ≡ 1 mod p. Multiplying both sides by a⁻¹ gives the famous formula: a⁻¹ ≡ a^(p-2) mod p So modInverse(a, p) is simply modPow(a, p - 2, p) in O(log p) time! After precomputing fact[0..N] in O(N) time, any C(n, r) mod p query runs in O(log p) time (or O(1) if invFact[0..N] is also precomputed).

Counting Questions from Placement Tests

Three classic placement question families reduce directly to C(n, r):

PlacementCounts.javaJava
public class PlacementCounts {    static long nCr(int n, int r) {        long result = 1;        for (int i = 1; i <= r; i++) {            result = result * (n - r + i) / i;        }        return result;    }
    public static void main(String[] args) {        System.out.println("3 x 3 grid paths: " + nCr(2 + 2, 2));        System.out.println("Handshakes among 10: " + nCr(10, 2));        System.out.println("5 coupons, 3 customers: " + nCr(3 + 5 - 1, 5));    }}
Output
3 x 3 grid paths: 6
Handshakes among 10: 45
5 coupons, 3 customers: 21
  • Grid Unique Paths: Moving from (0, 0) to (R - 1, C - 1) using only Right and Down takes (R - 1) Down moves and (C - 1) Right moves in some order — a total of C((R - 1) + (C - 1), R - 1) paths.
  • Pairs and Handshakes: Choosing 2 items out of n (such as handshakes in a room or pairs of equal elements with frequency f) is C(n, 2) = (n(n - 1))/2.
  • Stars and Bars: Distributing k identical items into n distinct bins (x₁ + x₂ + … + xₙ = k with xᵢ ≥ 0) arranges k stars and n - 1 dividing bars in C(n + k - 1, k) ways.

Next step

Check your understanding

10 quick questions