In Rust, handling vectors and performing mathematical calculations is a very common task, especially in data processing or scientific computing. If we want to calculate the sum of multiples of all elements in a vector, we can iterate over the vector and perform conditional checks on each element.
First, let me describe the basic steps:
- Create a vector.
- Iterate over each element in the vector.
- Check if the element is divisible by a specific number (e.g., 2, by verifying divisibility by 2).
- If it is, add it to the sum.
- Return the sum.
Here is a specific example where we calculate the sum of all multiples of 2 in a vector:
rustfn sum_of_multiples(numbers: &[i32], multiple_of: i32) -> i32 { numbers.iter() .filter(|&&x| x % multiple_of == 0) .sum() } fn main() { let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let sum = sum_of_multiples(&numbers, 2); println!("The sum of multiples of 2 is: {}", sum); }
In this example:
- The function
sum_of_multiplestakes a slice of integers and an integermultiple_of, representing the divisor for which we compute the sum. - We use
.iter()to obtain an iterator over the vector. - We apply
.filter()to retain only elements divisible bymultiple_of, using the conditionx % multiple_of == 0. - We use
.sum()to accumulate the values of the filtered elements. - In the
mainfunction, we create the vectornumbersand invokesum_of_multiplesto compute the sum of all multiples of 2.
When you run this program, it outputs The sum of multiples of 2 is: 30, as 2 + 4 + 6 + 8 + 10 = 30. This approach is both simple and efficient for solving such problems.
2024年7月1日 12:54 回复