Arithmetic operators in PowerShell - Time & Space Complexity
We want to understand how the time it takes to run arithmetic operations changes as we do more of them.
How does the number of calculations affect the total time?
Analyze the time complexity of the following code snippet.
$sum = 0
for ($i = 1; $i -le $n; $i++) {
$sum += $i * 2
}
Write-Output $sum
This code adds up the double of each number from 1 to n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying and adding inside a loop
- How many times: The loop runs once for each number from 1 to n
Each time we increase n, the loop runs more times, doing more calculations.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications and additions |
| 100 | 100 multiplications and additions |
| 1000 | 1000 multiplications and additions |
Pattern observation: The number of operations grows directly with n.
Time Complexity: O(n)
This means the time to finish grows in a straight line as we increase the number of calculations.
[X] Wrong: "Arithmetic operations inside a loop are instant and don't add to time."
[OK] Correct: Even simple math takes time, and doing it many times adds up as the input grows.
Knowing how loops with arithmetic grow helps you explain how your scripts will perform as data grows, a useful skill in many real tasks.
"What if we replaced the loop with a single formula to calculate the sum? How would the time complexity change?"