1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-19 14:16:55 +02:00
CodeWars/6kyu/irreducible_sum_of_rationals/solution.rs
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

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))
}