Strength reduction in Compiler Design - Time & Space Complexity
When a compiler changes expensive operations into cheaper ones, it affects how long the program takes to run.
We want to see how this change impacts the number of steps as input grows.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
int x = i * 5; // original expensive multiplication
// do something with x
}
// After strength reduction:
int x = 0;
for (int i = 0; i < n; i++) {
// replace multiplication with addition
// x = i * 5 becomes x += 5
// do something with x
x += 5;
}
This code replaces multiplication inside a loop with repeated addition to save time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs from 0 to n-1, repeating n times.
- How many times: Each iteration does one multiplication originally, replaced by one addition after strength reduction.
As n grows, the number of loop steps grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications or 10 additions |
| 100 | 100 multiplications or 100 additions |
| 1000 | 1000 multiplications or 1000 additions |
Pattern observation: The number of operations grows directly with n, but additions are cheaper than multiplications.
Time Complexity: O(n)
This means the total steps increase in a straight line as input size grows, but strength reduction makes each step faster.
[X] Wrong: "Strength reduction changes the overall time complexity from linear to constant."
[OK] Correct: The loop still runs n times, so the number of steps grows with n. Strength reduction only makes each step cheaper, not fewer.
Understanding how small changes in code affect time helps you explain optimization clearly and shows you think about efficiency practically.
"What if the loop ran n squared times instead of n? How would strength reduction affect the time complexity then?"