Introduction
Computers often perform slow operations repeatedly, which can make programs run slower than needed. Strength reduction helps by replacing these slow operations with faster ones, making the program run more efficiently.
Imagine you need to carry 10 boxes one by one to a truck. Instead of lifting each box individually (multiplying effort), you use a cart to carry several boxes at once by pushing it repeatedly (adding effort). This saves time and energy.
┌───────────────────────────────┐ │ Original Code │ │ for i in range(n): │ │ result = i * x │ └──────────────┬────────────────┘ │ ↓ ┌───────────────────────────────┐ │ After Strength Reduction │ │ temp = 0 │ │ for i in range(n): │ │ result = temp │ │ temp = temp + x │ └───────────────────────────────┘
def original_loop(x, n): results = [] for i in range(n): results.append(i * x) return results def strength_reduced_loop(x, n): results = [] temp = 0 for _ in range(n): results.append(temp) temp += x return results print(original_loop(3, 5)) print(strength_reduced_loop(3, 5))