← All lints

hand_rolled_pow

L0545Idiomswarn

hand-rolled fast power

a square-and-halve loop: pow_mod(b, e, m) or Mod<P> with **

Flagged
let (a, e): (0..=1000000000, 0..=1000000000000000000) = read()
fn power(b0: Int, e0: Int) -> Int:
    var b = b0 % 998244353
    var x = e0
    var r = 1
    while x > 0:
        if x % 2 == 1:
            r = r * b % 998244353
        b = b * b % 998244353
        x /= 2
    return r
print(power(a, e))
Write instead
let (a, e): (0..=1000000000, 0..=1000000000000000000) = read()
print(pow_mod(a, e, 998244353))

Why

Fast exponentiation by squaring (square the base, halve the exponent) is in the stdlib: pow_mod(b, e, m) from std.math computes b ** e % m in O(log⁡e)O(\log e) with a product that cannot overflow, and with a fixed modulus Mod<P> makes it Z(b) ** e. The lint fires on a function whose loop halves its exponent and squares its base. There is no automatic fix, since the call replaces the whole function.

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 x0: 1..=1000000000 = read()
fn halvings(start: Int) -> Int:
    var x = start
    var c = 0
    while x > 0:
        x /= 2
        c += 1
    return c
print(halvings(x0))

Turn it off

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

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