Skip to content

Instantly share code, notes, and snippets.

@BasixKOR
Last active February 23, 2020 09:49
Show Gist options
  • Save BasixKOR/e1143683cff43875d0b636e4d8bb2ce7 to your computer and use it in GitHub Desktop.
Save BasixKOR/e1143683cff43875d0b636e4d8bb2ce7 to your computer and use it in GitHub Desktop.
Euclidean algorithm
/// Recursive
fn gcd<T>(a: T, b: T) -> T where T: std::ops::Rem<Output = T> + Eq + From<u8> + Copy {
if b == T::from(0u8) {
a
} else {
gcd(b, a % b)
}
}
/// Iterated
fn gcd<T>(a: T, b: T) -> T where T: std::ops::Rem<Output = T> + Eq + From<u8> + Copy {
let mut snd = a;
let mut rem = b;
while rem != T::from(0u8) {
let r = snd % rem;
snd = rem;
rem = r;
}
rem
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment