Arithmetic operators in PHP - Time & Space Complexity
When using arithmetic operators in PHP, it's helpful to know how the time to run your code changes as you work with bigger numbers or more calculations.
We want to see how the number of operations grows when using arithmetic operators repeatedly.
Analyze the time complexity of the following code snippet.
$sum = 0;
for ($i = 1; $i <= $n; $i++) {
$sum += $i; // addition operation
}
echo $sum;
This code adds numbers from 1 up to n using the addition operator inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Addition inside the loop ($sum += $i)
- How many times: Exactly n times, once for each number from 1 to n
As n grows, the number of additions grows in 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 finish the additions grows in a straight line as the input size increases.
[X] Wrong: "Arithmetic operations like addition take constant time no matter how many times they run, so the whole loop is constant time."
[OK] Correct: While each addition is quick, doing it n times means the total time grows with n, so the loop is not constant time.
Understanding how simple arithmetic inside loops affects time helps you explain how your code scales, a key skill in many programming discussions.
"What if we replaced the addition inside the loop with a multiplication? How would the time complexity change?"