First R program in R Programming - Time & Space Complexity
We want to see how the time it takes to run a simple R program changes as we give it more work.
How does the program's running time grow when the input size grows?
Analyze the time complexity of the following code snippet.
# Print numbers from 1 to n
print_numbers <- function(n) {
for (i in 1:n) {
print(i)
}
}
print_numbers(5)
This code prints numbers from 1 up to n one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: It runs exactly n times, once for each number.
As n gets bigger, the program prints more numbers, so it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The time grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the program grows in a straight line with the input size.
[X] Wrong: "The program runs instantly no matter how big n is."
[OK] Correct: Each number must be printed one by one, so more numbers mean more time.
Understanding how loops affect running time is a key skill that helps you write efficient code and explain your thinking clearly.
"What if we changed the loop to print only every second number? How would the time complexity change?"