← All lints

ceil_div_formula

L0526Idiomswarn

Hand-written ceiling division

(a + b - 1) / b: the ceiling is ceil_div(a, b)

Flagged
let n: 1..=100 = read()
let k: 1..=10 = read()
print((n + k - 1) / k, (n + 4 - 1) / 4)
Write instead
let n: 1..=100 = read()
let k: 1..=10 = read()
print(ceil_div(n, k), ceil_div(n, 4))

Why

(a + b - 1) / b is the C++ way to round a quotient up. It names the divisor twice, can overflow where the answer does not, and is right only for b > 0. ceil_div(a, b) says what it computes, never overflows, and is right for every sign. The fix applies when b is a positive literal or a name whose range type starts at 1 or more, where both spellings agree for every a (integer / rounds down for a positive divisor), and when nothing in a or b calls anything.

The practice it serves

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

Not flagged

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

Near miss
let n: 1..=100 = read()
let k: 1..=10 = read()
let m: 0..=10 = read()
print((n + k - 2) / k, (n + k - 1) / 2, (n + k) / k)
if m > 0: print((n + m - 1) / m)

Turn it off

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

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