0
0
PHPprogramming~5 mins

Arithmetic operators in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Arithmetic operators
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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
How Execution Grows With Input

As n grows, the number of additions grows in the same way.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish the additions grows in a straight line as the input size increases.

Common Mistake

[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.

Interview Connect

Understanding how simple arithmetic inside loops affects time helps you explain how your code scales, a key skill in many programming discussions.

Self-Check

"What if we replaced the addition inside the loop with a multiplication? How would the time complexity change?"