Skip to main content

lib_jsl_number_theory/
integer_square_root.rs

1//! Exact integer square roots by Newton's method and by bisection.
2//!
3//! See the book entry [Divisibility and modular arithmetic](https://jwkunz.github.io/lib_jsl/book/number-theory/modular-arithmetic.html).
4
5/// Computes the integer square root of a `u128` using binary search (efficient, but slower)
6///
7/// The integer square root of `n` is defined as the largest integer `x`
8/// such that:
9///
10/// ```text
11/// x * x <= n
12/// ```
13///
14/// This function:
15/// - Works for the entire `u128` domain
16/// - Does not use floating-point arithmetic
17/// - Avoids overflow by using division-based comparisons
18/// - Runs in `O(log n)` time using binary search
19pub fn integer_square_root_binary_search(n: u128) -> u128 {
20    // Handle trivial cases explicitly.
21    if n < 2 {
22        return n;
23    }
24
25    // Search space:
26    // sqrt(n) is always <= n / 2 for n >= 2,
27    // but we can tighten this slightly by using n.
28    let mut low: u128 = 1;
29    let mut high: u128 = n;
30    let mut result: u128 = 0;
31
32    while low <= high {
33        let mid = low + (high - low) / 2;
34
35        // Compare mid * mid <= n without overflow.
36        if mid <= n / mid {
37            result = mid;
38            low = mid + 1;
39        } else {
40            high = mid - 1;
41        }
42    }
43
44    result
45}
46
47/// Computes the integer square root of a `u128` using the
48/// Newton–Raphson method (faster)
49///
50/// The integer square root of `n` is defined as the largest integer `x`
51/// such that:
52///
53/// ```text
54/// x * x <= n
55/// ```
56///
57/// This function:
58/// - Uses the Newton–Raphson iteration:
59///   x_{k+1} = (x_k + n / x_k) / 2
60/// - Starts above the root, where the iterates decrease monotonically to
61///   ⌊√n⌋, and stops at the first iterate that does not decrease (starting
62///   below the root, the iteration can alternate between ⌊√n⌋ and ⌊√n⌋ + 1)
63/// - Avoids overflow by computing `n / x_k`
64/// - Converges very quickly in `O(log log n)` iterations
65pub fn integer_square_root_newton(n: u128) -> u128 {
66    if n < 2 {
67        return n;
68    }
69
70    // 2^⌈bits/2⌉ is at least √n.
71    // ANCHOR: newton_isqrt
72    let bits = 128 - n.leading_zeros();
73    let mut x = 1u128 << bits.div_ceil(2);
74
75    loop {
76        let next = (x + n / x) / 2;
77        if next >= x {
78            return x;
79        }
80        x = next;
81    }
82    // ANCHOR_END: newton_isqrt
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89
90
91    #[test]
92    fn newton_terminates_and_agrees_with_binary_search() {
93        // n = k² − 1 used to make the iteration alternate between k − 1 and k forever.
94        for n in 0..20_000u128 {
95            assert_eq!(integer_square_root_newton(n), integer_square_root_binary_search(n), "n = {n}");
96        }
97        for k in [3u128, 1 << 20, 1 << 40, (1 << 63) + 12345, u64::MAX as u128] {
98            for n in [k * k - 1, k * k, k * k + 1] {
99                let r = integer_square_root_newton(n);
100                assert!(r * r <= n && (r + 1).checked_mul(r + 1).is_none_or(|v| v > n), "n = {n}");
101            }
102        }
103        assert_eq!(integer_square_root_newton(u128::MAX), u64::MAX as u128);
104    }
105
106    #[test]
107    fn test_integer_square_root_binary_search() {
108        for i in 0u128..1000000 {
109            let sq = i * i;
110            assert_eq!(integer_square_root_binary_search(sq), i); // Slow
111        }
112    }
113
114
115    #[test]
116    fn test_integer_square_root_newton() {
117        for i in 0u128..1000000 {
118            let sq = i * i;
119            assert_eq!(integer_square_root_newton(sq), i); // Fast
120        }
121    }
122
123}