amarao: (Default)
[personal profile] amarao

Но вот самоизобретённый алгоритм поиска квадратного корня для int'а (на входе только положительные числа). Надо сказать, от Си его отличает только большая словесность (Ordering::Greater вместо 1).

use std::cmp::Ordering;

pub fn my_sqrt(x: i32) -> i32 {
    if x == 0 || x == 1{
        return x;
    }
    let x = x as u32;
    let sig_bit_count = 31 - x.leading_zeros();
    let mut working_bit = sig_bit_count / 2;
    let mut root = 1u32 << working_bit;
    while working_bit > 0 {
        working_bit -= 1;                    
        let candidate = 1 << working_bit; 
        root += match ((root + candidate) * (root + candidate)).cmp(&x) {
            Ordering::Equal | Ordering::Less => candidate,
            Ordering::Greater => 0,
        }
    }
    root as i32
}
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

amarao: (Default)
amarao

April 2026

S M T W T F S
   1234
567 891011
12131415161718
19202122232425
2627282930  

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Apr. 14th, 2026 02:58 am
Powered by Dreamwidth Studios