Math Fundamentals18 sections · 814 units
Open in Course

Roots and Precision

Floating-point issues

Computing n\sqrt{n} with floating-point math can give wrong answers. sqrt(49) might return 6.9999999996.999999999 instead of 77. If you cast that to an integer, you get 66.

For integer square root, use binary search instead. Search for the largest kk where k2nk^2 \leq n. This avoids floating-point errors and runs in O(logn)O(\log n) time, O(1)O(1) space.

Newton's method is another option: start with guess xx, then set x=(x+n/x)/2x = (x + n/x) / 2 using integer division. It converges fast, usually under 3030 iterations even for 6464-bit inputs.

When a problem asks "is nn a perfect square?" or "find the integer square root," avoid math.sqrt. Use binary search or Newton's method with integer arithmetic.