Arithmetic operators in R Programming - Time & Space Complexity
We want to see how the time to do arithmetic operations changes as we work with more numbers.
How does the number of calculations grow when we increase the input size?
Analyze the time complexity of the following code snippet.
numbers <- 1:1000
result <- 0
for (num in numbers) {
result <- result + num * 2
}
This code multiplies each number by 2 and adds it to a total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying and adding each number in the list.
- How many times: Once for each number in the list (1000 times in this example).
As the list gets longer, the number of calculations grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications and additions |
| 100 | 100 multiplications and additions |
| 1000 | 1000 multiplications and additions |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items you process.
[X] Wrong: "Arithmetic operations inside a loop are instant and don't add up."
[OK] Correct: Even simple math done many times adds up, so the total time grows with the number of operations.
Understanding how simple repeated calculations add up helps you explain how programs handle data efficiently.
"What if we replaced the loop with a vectorized operation? How would the time complexity change?"