leetcode_rust/
sqrt_x.rs

1#![allow(dead_code)]
2
3// newton method
4pub fn my_sqrt(x: i32) -> i32 {
5    if x <= 1 {
6        x
7    } else {
8        let x = x as f64;
9        let mut res = x;
10        while res > x / res {
11            res = (res + x / res) / 2.0;
12            res = res.floor();
13        }
14        res as i32
15    }
16}
17
18// newton method using other way of writing
19pub fn my_sqrt2(x: i32) -> i32 {
20    let x = x as f64;
21    let (mut a1, mut a2) = (1.0f64, 0.0f64);
22
23    while (a1 - a2).abs() >= 0.1 {
24        a2 = a1;
25        a1 = (a1 + x / a1) / 2.0;
26    }
27    a1 as i32
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn test1() {
36        assert_eq!(my_sqrt(8), 2);
37        assert_eq!(my_sqrt(99), 9);
38    }
39
40    #[test]
41    fn test2() {
42        assert_eq!(my_sqrt2(8), 2);
43        assert_eq!(my_sqrt2(99), 9);
44    }
45}