Solve day 8
This commit is contained in:
parent
f16fae23ab
commit
9dbfc6043a
4 changed files with 207 additions and 2 deletions
50
src/lib.rs
50
src/lib.rs
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue