Numeric type in R Programming - Time & Space Complexity
We want to understand how the time to work with numeric types changes as the size of the numbers or data grows.
How does the time needed to perform numeric operations grow when we handle bigger or more numbers?
Analyze the time complexity of the following code snippet.
# Sum numbers from 1 to n
sum_numbers <- function(n) {
total <- 0
for (i in 1:n) {
total <- total + i
}
return(total)
}
result <- sum_numbers(1000)
print(result)
This code adds all numbers from 1 up to n and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a number to the total inside a loop.
- How many times: The loop runs 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 number of operations grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to complete the sum grows in a straight line as the input size grows.
[X] Wrong: "Adding numbers from 1 to n takes the same time no matter how big n is."
[OK] Correct: Each number must be added one by one, so more numbers mean more time.
Understanding how loops over numbers affect time helps you explain and improve code that processes data step by step.
"What if we used a built-in function that sums numbers without a loop? How would the time complexity change?"