乐闻世界logo
搜索文章和话题

How do I sum a vector using fold using Rust?

1个答案

1

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:

  1. Create a vector.
  2. Iterate over each element in the vector.
  3. Check if the element is divisible by a specific number (e.g., 2, by verifying divisibility by 2).
  4. If it is, add it to the sum.
  5. Return the sum.

Here is a specific example where we calculate the sum of all multiples of 2 in a vector:

rust
fn 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_multiples takes a slice of integers and an integer multiple_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 by multiple_of, using the condition x % multiple_of == 0.
  • We use .sum() to accumulate the values of the filtered elements.
  • In the main function, we create the vector numbers and invoke sum_of_multiples to 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 回复

你的答案