1
0
Fork 0

Solve day 8

This commit is contained in:
Lars Martens 2023-12-08 14:28:23 +01:00
parent f16fae23ab
commit 9dbfc6043a
Signed by: haselkern
GPG key ID: B5CF1F363C179AD4
4 changed files with 207 additions and 2 deletions

View file

@ -1,5 +1,8 @@
use std::fmt::{Debug, Display};
use std::str::FromStr;
use std::{
fmt::{Debug, Display},
ops::{Div, Mul, Rem},
str::FromStr,
};
/// Parse a whitespace separated list of things.
///
@ -27,3 +30,46 @@ where
{
format!("{a}{b}").parse().unwrap()
}
/// Return the greatest common divisor.
///
/// https://en.wikipedia.org/wiki/Euclidean_algorithm
pub fn gcd<T>(mut a: T, mut b: T) -> T
where
T: PartialEq + Default + Rem<Output = T> + Copy,
{
let zero = T::default();
while b != zero {
(a, b) = (b, a % b);
}
a
}
/// Return the least common multiple.
///
/// https://en.wikipedia.org/wiki/Least_common_multiple
pub fn lcm<T>(a: T, b: T) -> T
where
T: PartialEq + Default + Rem<Output = T> + Div<Output = T> + Mul<Output = T> + Copy,
{
let gcd = gcd(a, b);
a / gcd * b
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn test_gcd() {
assert_eq!(gcd(252, 105), 21);
assert_eq!(gcd(105, 252), 21);
}
#[test]
fn test_lcm() {
assert_eq!(lcm(4, 6), 12);
assert_eq!(lcm(6, 4), 12);
}
}