← All lints

binom_by_hand

L0557Idiomswarn

Binomial from factorial tables by hand

fact[a] * inv(fact[b]) * inv(fact[a - b]): Comb<Z>(n).choose(a, b)

Flagged
let (a, b): (0..=1000, 0..=1000) = read()
var fact: List<Int> = [1]
for i in 1..=1000:
    fact.push(fact[i - 1] * i % 998244353)
fn inv(x: Int) -> Int = pow_mod(x, 998244353 - 2, 998244353)
if b > a:
    print(0)
else:
    print(fact[a] * inv(fact[b]) % 998244353 * inv(fact[a - b]) % 998244353)
Write instead
let (a, b): (0..=1000, 0..=1000) = read()
type Z = Mod<998244353>
let c = Comb<Z>(1000)
print(c.choose(a, b))

Why

n choose k from a factorial table and modular inverses (fact[n] * inv(fact[k]) % P * inv(fact[n - k]) % P) repeats the modulus, the reduction after each product and the k > n case at every use. Comb<Z>(limit) from std.mod, with type Z = Mod<P>, keeps the tables and the inverses: c.choose(n, k) is the binomial and is 0 when k > n. There is no automatic fix, because the tables and the modulus have to move into the type.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let (a, b): (0..=1000, 0..=1000) = read()
var fact: List<Int> = [1]
for i in 1..=1000:
    fact.push(fact[i - 1] * i % 998244353)
print(fact[a] * fact[b] % 998244353)
// A difference of prefix sums at `x`, `n` and `n - x` is not a binomial.
print(fact[b] - (fact[a] - fact[a - b]))

Turn it off

For one block, wrap it in with lint(binom_by_hand: allow):. For a project, add binom_by_hand = "allow" under [lints] in cp.toml.

Generated from spec/lints/binom_by_hand, the same record the linter is built from.