Square root of a u128

How can the square root of a u128 be calculated? The resulting number can be a u128 after some rounding.

f64 has a f64::sqrt function, but I dont think we should be converting u128 to f64.


Solution 1:

You can use the Roots trait from the num crate (or directly from the num-integer crate):

pub fn sqrt(&self) -> Self

Returns the truncated principal square root of an integer – ⌊√x⌋

This is solving for r in r² = x, rounding toward zero. The result will satisfy r² ≤ x < (r+1)².

use num::integer::Roots; // 0.4.0

fn main() {
    let a: u128 = 42;
    let b = a.sqrt();
    
    assert!(b == 6);
}