Arithmetic operators in Rust - Time & Space Complexity
We want to see how the time needed to do arithmetic operations changes as the numbers get bigger.
How does the cost grow when we do simple math in code?
Analyze the time complexity of the following code snippet.
fn sum_numbers(numbers: &[i32]) -> i32 {
let mut total = 0;
for &num in numbers {
total += num;
}
total
}
This code adds up all numbers in a list and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the total.
- How many times: Once for every number in the list.
As the list gets longer, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line as the list gets bigger.
[X] Wrong: "Adding numbers is always instant, no matter how many there are."
[OK] Correct: Each number must be added one by one, so more numbers mean more work.
Understanding how simple math operations scale helps you explain how your code handles bigger data smoothly.
"What if we used multiplication instead of addition for each number? How would the time complexity change?"