mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-08 18:49:07 +01:00
28 lines
558 B
Rust
28 lines
558 B
Rust
fn gcd(mut a: i64, mut b: i64) -> i64 {
|
|
while b != 0 {
|
|
let t = b;
|
|
b = a % b;
|
|
a = t;
|
|
}
|
|
|
|
a
|
|
}
|
|
|
|
fn lcm(a: i64, b: i64) -> i64 {
|
|
(a*b).abs() / gcd(a, b)
|
|
}
|
|
|
|
fn sum_fracts(l: Vec<(i64, i64)>) -> Option<(i64, i64)> {
|
|
if l.is_empty() {
|
|
return None;
|
|
}
|
|
|
|
let denom = l.iter().fold(1, |a, b| lcm(a, b.1));
|
|
|
|
let (num, den) = l.iter().fold((0, denom), |runner, frac|
|
|
(runner.0 + (frac.0 * denom / frac.1), denom)
|
|
);
|
|
|
|
let divisor = gcd(num, den);
|
|
Some((num / divisor, den / divisor))
|
|
}
|