Code Optimization & Time Complexity: A Simple Example
When we start coding, we often solve problems in the most straightforward way. But as we grow, we learn to optimize our code for better performance and readability.
In this blog, I’ll show you how we can improve code step by step using a simple example:
👉 Find the sum of all numbers between 1 and 100 that are divisible by 3.
🐣 Beginner Approach
The first thought most beginners have:
- Loop from 1 to 100
- Check if the number is divisible by 3
- If yes, add it to the sum
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
sum = sum + i;
}
}✅ Works fine but notice:
- Loop runs 100 times.
- Every number is checked using
i % 3. - Time Complexity: O(n)
⚡ Intermediate Approach
A slightly optimized way:
- Instead of checking every number, start from 3 and keep adding 3 each time (
i = i + 3). - This way, every number is already divisible by 3, no
ifcondition needed.
int sum = 0;
for (int i = 3; i <= 100; i = i + 3) {
sum = sum + i;
}✅ Better because:
- Loop runs only 33 times (3, 6, 9, …, 99).
- Condition check removed.
- Time Complexity: O(n/3) → still O(n), but fewer operations.
🎯 Advanced Approach
Now let’s use mathematics.
We know the sum of an arithmetic progression (AP):
Where:
a= first term (3)d= common difference (3)n= number of terms
👉 In our case:
- Last multiple of 3 ≤ 100 is 99.
- Number of terms
n = 99/3 = 33.
So:
✅ Most optimized
- No loop at all.
- Just a formula, constant time.
- Time Complexity: O(1)
🔥 Key Takeaways
- Beginner: Loops through all numbers → O(n)
- Intermediate: Loops fewer times → O(n/3) (still O(n))
- Advanced: Formula, no loop → O(1)
👉 This shows how thinking about the problem differently can turn a loop-heavy solution into an instant calculation.
Get Haresh Prajapati’s stories in your inbox
Join Medium for free to get updates from this writer.
⚡ Optimization is not just about speed, but also about cleaner and smarter code.
Final Thought
Next time you write code, ask yourself:
- Am I looping more than necessary?
- Can I reduce checks inside the loop?
- Is there a more efficient way than iterating step by step?
The more you practice, the more your brain will automatically look for these optimizations.
💡 Start small, think smart, and code better every day.






