← All lints

manual_mod_reduce

L0531Idiomswarn

Modular arithmetic by hand

a * b % 1000000007 after each product: type Z = Mod<1000000007>

Flagged
let (a, b): (0..=1000000006, 0..=1000000006) = read()
let p = a * b % 1000000007
let q = p * p % 1000000007
print(p, q)
Write instead
type Z = Mod<1000000007>
let (a, b): (0..=1000000006, 0..=1000000006) = read()
let p = Z(a) * Z(b)
let q = p * p
print(p, q)

Why

C++ works modulo a prime by writing % MOD after every product (f = f * i % 1000000007). Each one is a place to forget it, and a forgotten one overflows or prints a wrong answer only on large tests. Mod<P> from std.mod is an integer modulo P that reduces after every *, + and - (subtraction never goes negative), so the arithmetic reads like the formula: declare type Z = Mod<1000000007> once, wrap the inputs (Z(a)), and compute in Z. Division by a Z multiplies by its inverse. The lint fires on x * y % P with a literal P of at least 10**8, once per file at the first such reduction. It has no fix: which values become Z is a choice of the whole program.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.mod: modular arithmetic and combinatorics.

Not flagged

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

Near miss
let (a, b): (0..=1000000006, 0..=1000000006) = read()
print((a + b) % 1000000007, a * b % 10)

Turn it off

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

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