Divisible Drama — Who’s In, Who’s Out?
Divisible Drama — Who’s In, Who’s Out?
Problem Statement
You’re given two positive integers n
and m
.
-
num1 = sum of all numbers from
1
ton
not divisible bym
-
num2 = sum of all numbers from
1
ton
divisible bym
Your mission, should you choose to accept it:
Return num1 - num2
Example
Best Data Structure for Solving the Problem
This one’s a math. Why overthink it when Gauss already gave us the formula for sum of 1 to n?
Different Approaches (from Brute Force to Optimized)
Approach 1: Brute Force (aka List & Sum Vibes)
Loop from 1
to n
, split the nums based on whether they’re divisible by m
, and sum them up.
Approach 2: Math
Instead of looping through each number like it's 2010, we flex some math muscles:
-
totalSum = n * (n + 1) / 2
← classic Gauss move -
num2 = m * k * (k + 1) / 2
wherek = n / m
← sum of all multiples ofm
⚠️ Common Mistakes and Pitfalls
-
Only subtracting once:
totalSum - divisibleSum
← WRONG, needs to betotalSum - 2 * divisibleSum
-
Integer division messing with your results (but we're safe here)
-
Not spotting the math shortcut and brute-forcing everything
📊 Time and Space Complexity Analysis
Approach | Time Complexity | Space Complexity |
---|---|---|
Brute Force | O(n) | O(1) |
Math Optimized | O(1) | O(1) |
🌍 Real-World Applications
-
Financial Planning: Filtering monthly transactions divisible by fixed costs (like rent/utilities)
-
Digital Coupons: Separating discounts applicable on every nth order
-
Productivity Tools: Time tracking, like focusing only on “non-distraction” intervals
-
Educational Apps: Rewarding users for days not divisible by skipped days
I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!
Signing off!!
Master DSA One Problem at a Time :)
Comments
Post a Comment