[Rust] GCD generic implementation

Правка en1, от satylogin, 2021-06-14 16:43:01

I was trying to come up with a generic implementation of gcd in rust that I could use by copy pasting without worrying about data type. I finally have something useful that works on sane data types.

I am sharing the implementation in case someone needs it

/// Calculates gcd for same types T that implements required traits.
/// The current implementation is tested on i32, u32, i64, u64, usize, isize
/// For any other type T, the behaviour is undefined
pub fn gcd<T>(a: T, b: T) -> T
where
    T: std::cmp::PartialEq + std::ops::Rem<Output = T> + Default + Copy,
{
    // for our required types, default evalutaes to 0 at compile time.
    // and thus have 0 cost abstraction.
    if b == T::default() {
        a
    } else {
        gcd(b, a % b)
    }
}

I am uploading such generic things in my repo as and when I need something: https://github.com/satylogin/cp-lib/

Теги rust, gcd, maths, generics

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский satylogin 2021-06-14 16:43:01 945 Initial revision (published)