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

29 lines
771 B
Rust

use std::vec::Vec;
fn is_prime(n: i64) -> bool {
match n {
x if x % 2 == 0 => x == 2,
_ => {
let max_value = (n as f64).sqrt().ceil() as i64;
(3..max_value + 1).step_by(2).all(|i| n % i != 0)
}
}
}
pub fn sum_of_divided(l: Vec<i64>) -> Vec<(i64, i64)> {
let max_value = l.iter().max_by_key(|x| x.abs());
match max_value {
Some(max_val) => (2..max_val.abs() + 1)
.filter(|&i| is_prime(i) && l.iter().any(|x| x % i == 0))
.map(|i| {
(
i,
l.iter()
.fold(0, |acc, &x| acc + if x % i == 0 { x } else { 0 }),
)
})
.collect(),
None => vec![],
}
}