Algo-Sim › Math & Geometry

nCr mod p

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Binomial coefficients modulo the prime 10⁹ + 7: factorials, then inverse factorials from one Fermat inverse via fast power.

Problem

Given n and r, return C(n, r) = n! / (r! · (n − r)!) modulo p = 10⁹ + 7. Return 0 when r is outside 0..n. (A textbook building block for counting problems; not a LeetCode problem by itself.)

Constraints

Edge cases to test

Follow-up questions

Why one Fermat inverse, not n of them?
Compute invFact[n] = fact[n]^(p − 2) once, then invFact[i − 1] = invFact[i] · i: O(n + log p).
What if the modulus is not prime?
Fermat inverses don’t exist for every value; use Pascal’s triangle (O(n²)) or the Chinese remainder theorem over prime-power factors.

Solution

Java

static final long MOD = 1_000_000_007L;

public long nCr(int n, int r) {
    if (r < 0 || r > n) return 0;
    long[] fact = new long[n + 1];
    fact[0] = 1;
    for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i % MOD;
    long[] inv = new long[n + 1];
    // Fermat: for prime p, a^(p-2) is the inverse of a mod p.
    inv[n] = power(fact[n], MOD - 2);
    for (int i = n; i > 0; i--) inv[i - 1] = inv[i] * i % MOD;
    return fact[n] * inv[r] % MOD * inv[n - r] % MOD;
}

long power(long a, long e) {
    long result = 1;
    a %= MOD;
    while (e > 0) {
        if ((e & 1) == 1) result = result * a % MOD;
        a = a * a % MOD;
        e >>= 1;
    }
    return result;
}

Python

MOD = 1_000_000_007


def n_cr(n, r):
    if r < 0 or r > n:
        return 0
    fact = [1] * (n + 1)
    for i in range(1, n + 1):
        fact[i] = fact[i - 1] * i % MOD
    inv = [1] * (n + 1)
    # Fermat: for prime p, a^(p-2) is the inverse of a mod p.
    inv[n] = power(fact[n], MOD - 2)
    for i in range(n, 0, -1):
        inv[i - 1] = inv[i] * i % MOD
    return fact[n] * inv[r] % MOD * inv[n - r] % MOD


def power(a, e):
    result, a = 1, a % MOD
    while e:
        if e & 1:
            result = result * a % MOD
        a = a * a % MOD
        e >>= 1
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
    static constexpr long long MOD = 1'000'000'007LL;

    long long power(long long a, long long e) {
        long long result = 1;
        a %= MOD;
        while (e > 0) {
            if (e & 1) result = result * a % MOD;
            a = a * a % MOD;
            e >>= 1;
        }
        return result;
    }

  public:
    long long nCr(int n, int r) {
        if (r < 0 || r > n) return 0;
        vector<long long> fact(n + 1), inv(n + 1);
        fact[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i % MOD;
        // Fermat: for prime p, a^(p-2) is the inverse of a mod p.
        inv[n] = power(fact[n], MOD - 2);
        for (int i = n; i > 0; i--) inv[i - 1] = inv[i] * i % MOD;
        return fact[n] * inv[r] % MOD * inv[n - r] % MOD;
    }
};

More Math & Geometry problems