3

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830

1 Answers1

5

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);
}
kmdreko
  • 42,554
  • 6
  • 57
  • 106