Summing Multiples of Three with For Loops in Rust
This challenge will test your understanding of for loops in Rust, specifically how to iterate over ranges and perform conditional logic within a loop. You'll be tasked with calculating the sum of all numbers within a given range that are divisible by three. This is a fundamental problem that helps solidify your grasp of iteration and basic arithmetic operations in Rust.
Problem Description
Your goal is to write a Rust function that takes two unsigned 32-bit integers, start and end, representing the inclusive bounds of a range. The function should calculate and return the sum of all numbers within this range (including start and end) that are perfectly divisible by 3.
Key Requirements:
- Iterate through the numbers from
starttoend(inclusive). - For each number, check if it is divisible by 3.
- If a number is divisible by 3, add it to a running total.
- Return the final sum.
Expected Behavior:
The function should accurately sum all multiples of 3 within the specified range.
Edge Cases to Consider:
- What happens if
startis greater thanend? (The loop should not execute, and the sum should be 0). - What if the range contains no multiples of 3? (The sum should be 0).
- What if
startandendare the same and divisible by 3? (The sum should be that number).
Examples
Example 1:
Input: start = 1, end = 10
Output: 18
Explanation: The numbers in the range 1 to 10 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The numbers divisible by 3 are 3, 6, and 9. Their sum is 3 + 6 + 9 = 18.
Example 2:
Input: start = 15, end = 30
Output: 165
Explanation: The multiples of 3 in this range are 15, 18, 21, 24, 27, and 30. Their sum is 15 + 18 + 21 + 24 + 27 + 30 = 165.
Example 3:
Input: start = 7, end = 8
Output: 0
Explanation: There are no numbers divisible by 3 in the range 7 to 8.
Example 4:
Input: start = 5, end = 3
Output: 0
Explanation: Since the start is greater than the end, the loop does not execute, and the sum remains 0.
Constraints
startandendwill beu32(unsigned 32-bit integers).- The maximum value for
startandendisu32::MAX. - The sum of the multiples of three will not exceed
u32::MAX.
Notes
- Rust's
forloop syntax is ideal for iterating over ranges. Remember how to define an inclusive range. - The modulo operator (
%) is your friend for checking divisibility. - Consider how to initialize your sum variable.