awelgorithms

Integer answers avoid floats

Updated

If the answer must be an integer, search integer mids on an integer range. Predicate m*m ≤ n (or m*m < n) uses integer multiply. Do not binary-search reals and then round — off-by-one and overflow-in-float both show up.

What to focus on

lo, hi, mid stay ints. Stop with L > R or with a stored best. Integer square root of 9 is 3 via m*m ≤ 9, never 3.0.

Worked examples

isqrt 9

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], n=9, last m with m*m ≤ 9
  1. L=0 R=9 mid=4, 16>9, R=3
  2. mid=1, 1≤9, L=2
  3. mid=2, 4≤9, L=3
  4. mid=3, 9≤9, L=4 > R=3

Result: answer 3, all integer

isqrt 2

a = [0, 1, 2], n=2, last m with m*m ≤ 2
  1. mid=1, 1≤2, keep 1 and go right
  2. mid=2, 4>2, drop 2

Result: answer 1, not 1.414

float trap

a = [0, 9] real interval then round
  1. mid wanders near 3.0
  2. rounding can land on 2 or 4 if you stop early

Result: use integer m*m ≤ n instead

Try it

Write lastM(n). n is a non-negative integer. L, mid, and R are integer candidate values, not array indices. pred(m) is m*m ≤ n and returns true or false. Return the last m with m*m ≤ n. n=9 → 3 n=2 → 1, not 1.414 Real-then-round can land on 2 or 4

n is a non-negative integer. The search range is integers 0..n. pred returns true or false.