[Rust] GCD generic implementation

Revision en1, by 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/

Tags rust, gcd, maths, generics

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English satylogin 2021-06-14 16:43:01 945 Initial revision (published)