Integer type in R Programming - Time & Space Complexity
When working with integers in R, it's helpful to know how operations on them grow as numbers get bigger.
We want to see how the time to do integer operations changes with input size.
Analyze the time complexity of the following code snippet.
# Sum integers from 1 to n
sum_integers <- function(n) {
total <- 0L
for (i in 1:n) {
total <- total + i
}
return(total)
}
This code adds up all integers from 1 to n using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an integer to total inside the loop.
- How many times: Exactly n times, once for each number from 1 to n.
As n grows, 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 n; double n means double the additions.
Time Complexity: O(n)
This means the time to sum integers grows in a straight line with the number of integers.
[X] Wrong: "Adding integers is always instant, so time doesn't grow with n."
[OK] Correct: Each addition takes a tiny bit of time, so more numbers mean more additions and more total time.
Understanding how simple integer operations scale helps you reason about bigger problems and write efficient code.
"What if we used a built-in function like sum() instead of a loop? How would the time complexity change?"