← All lints

float_sqrt_for_int

L0529Correctnesswarn

Integer square root through F64

floor(sqrt(n)) on an Int: the exact root is n.isqrt

Flagged
let n: 1..=10**12 = read()
let m: 1..=10**6 = read()
print(floor(sqrt(n)), trunc(sqrt(F64(m))), floor(m.sqrt), Int(sqrt(F64(n)).floor))
Write instead
let n: 1..=10**12 = read()
let m: 1..=10**6 = read()
print(n.isqrt, m.isqrt, m.isqrt, n.isqrt)

Why

floor(sqrt(n)) is C++'s (int)sqrt(n): it rounds n to an F64, takes a float root and rounds down. Past 2**52 the float root can land just under a whole number, so the result is one too small for some perfect squares (and one too big just below them). n.isqrt (std.math) is the exact integer square root, the largest r with r * r <= n, for every Int. The fix applies when the operand is a name or field whose type is Int or an integer range, written floor or trunc of sqrt(n), sqrt(F64(n)) or n.sqrt.

The practice it serves

Code that is wrong or almost certainly a bug. Denied by cpl lint. Family: S.math.

Not flagged

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

Near miss
let n: 1..=10**12 = read()
let x: F64 = read()
print(floor(sqrt(x)), floor(sqrt(n) * 2.0), round(sqrt(n)))

Turn it off

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

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