← All lints

loop_invariant_mod_div

L0415Performancewarn

Loop-invariant Mod divisor inside loop

a Mod<P> division by a loop-invariant value computes an O(log⁡P)O(\log P) inverse every iteration

Flagged
type Z = Mod<998_244_353>
let d = Z(3)
var xs = [Z(1), Z(2), Z(3)]
for i in 0..xs.len:
    xs[i] /= d
print(xs)
Write instead
type Z = Mod<998_244_353>
let d = Z(3)
var xs = [Z(1), Z(2), Z(3)]
let inv_d = d.inv()
for i in 0..xs.len:
    xs[i] *= inv_d
print(xs)

Why

Dividing a Mod<P> value computes an O(log⁡P)O(\log P) modular inverse on every iteration. When the divisor does not change inside the loop, hoist let inv_d = d.inv before the loop and multiply by inv_d instead.

The practice it serves

Code that does more work than it needs to. Family: S.mod: modular arithmetic and combinatorics.

Not flagged

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

Near miss
type Z = Mod<998_244_353>
var xs = [Z(1), Z(2), Z(3)]
for i in 0..xs.len:
    xs[i] = xs[i] / xs[0]
print(xs)

Turn it off

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

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