Divisible and Non-divisible Sums Difference - Problem

You're given two positive integers n and m. Your task is to calculate the difference between two special sums:

  • num1: Sum of all integers from 1 to n that are NOT divisible by m
  • num2: Sum of all integers from 1 to n that ARE divisible by m

Return num1 - num2.

Example: If n=10 and m=3, then:
• Numbers NOT divisible by 3: {1,2,4,5,7,8,10} → sum = 37
• Numbers divisible by 3: {3,6,9} → sum = 18
• Answer: 37 - 18 = 19

Input & Output

example_1.py — Basic case
$ Input: n = 10, m = 3
Output: 19
💡 Note: Numbers 1-10 not divisible by 3: {1,2,4,5,7,8,10} sum=37. Divisible by 3: {3,6,9} sum=18. Result: 37-18=19
example_2.py — Small values
$ Input: n = 5, m = 6
Output: 15
💡 Note: Numbers 1-5 not divisible by 6: {1,2,3,4,5} sum=15. No numbers divisible by 6, sum=0. Result: 15-0=15
example_3.py — All divisible
$ Input: n = 4, m = 1
Output: -10
💡 Note: All numbers 1-4 are divisible by 1: {1,2,3,4} sum=10. Non-divisible sum=0. Result: 0-10=-10

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ 1000
  • n and m are positive integers

Visualization

Tap to expand
Approach ComparisonBrute Force O(n)for i = 1 to n:if i % m == 0:add to sum2else add to sum1n iterations requiredMathematical O(1)total = n*(n+1)/2count = n/msum2 = m*count*(count+1)/2sum1 = total - sum24 operations onlyPerformance ComparisonFor n = 1,000,000:• Brute Force: 1M iterations ⏱️• Mathematical: 4 operations ⚡250,000x faster!
Understanding the Visualization
1
Brute Force
Iterate through all n numbers, checking each one
2
Mathematical
Use arithmetic series formulas for instant calculation
3
Time Complexity
O(n) vs O(1) - dramatic difference for large inputs
Key Takeaway
🎯 Key Insight: Mathematical formulas can replace iteration when dealing with arithmetic sequences, providing dramatic performance improvements from O(n) to O(1).
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 10
28.7K Views
Medium Frequency
~8 min Avg. Time
956 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen