Divisible and Non-divisible Sums Difference - Problem

You are given positive integers n and m. Define two integers as follows:

  • num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
  • num2: The sum of all integers in the range [1, n] (both inclusive) that are divisible by m.

Return the integer num1 - num2.

Input & Output

Example 1 — Basic Case
$ Input: n = 10, m = 3
Output: 19
💡 Note: Numbers 1-10: [1,2,3,4,5,6,7,8,9,10]. Divisible by 3: [3,6,9] sum=18. Not divisible: [1,2,4,5,7,8,10] sum=37. Return 37-18=19.
Example 2 — Small Range
$ Input: n = 5, m = 6
Output: 15
💡 Note: Numbers 1-5: [1,2,3,4,5]. None divisible by 6, so num2=0. num1=1+2+3+4+5=15. Return 15-0=15.
Example 3 — Perfect Divisor
$ Input: n = 5, m = 1
Output: -15
💡 Note: All numbers [1,2,3,4,5] divisible by 1, so num1=0, num2=15. Return 0-15=-15.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ 1000

Visualization

Tap to expand
Range [1,10] with m=3Split numbers by divisibility by 3Not Divisible by 3[1, 2, 4, 5, 7, 8, 10]Divisible by 3[3, 6, 9]Sum = 37Sum = 18num1 - num2 = 37 - 18Result: 19
Understanding the Visualization
1
Input
Given n=10, m=3, range [1,10]
2
Categorize
Split by divisibility by m
3
Calculate
Find difference of sums
Key Takeaway
🎯 Key Insight: Use arithmetic sequence formulas to calculate sums in O(1) time instead of iterating through all numbers
Asked in
Microsoft 15 Apple 12
15.2K Views
Medium Frequency
~8 min Avg. Time
680 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