pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 {
(1..limit)
.filter(|&n| factors.iter().any(|&factor| factor != 0 && n % factor == 0))
.sum()
}
Instead of implementing the steps in the exercise description, this approach uses another angle:
- Iterate all numbers between 1 (inclusive) and
limit(exclusive) - Keep only numbers which have at least one factor in
factors(automatically avoiding any duplicates) - Calculate the sum of all numbers kept
After creating our range, we use filter to keep only matching multiples.
To detect the multiples, we scan the factors and use any to check if at least one is a factor of the number we're checking.
(any is short-circuiting: it stops as soon as it finds one compatible factor.)
Finally, once we have the multiples, we can compute the sum easily using sum.
28th Aug 2024
·
Found it useful?