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
Divisible and Non-divisible Sums Difference INPUT Range [1, n] where n=10, m=3 1 2 3 4 5 6 7 8 9 10 Not divisible by 3 Divisible by 3 n = 10 m = 3 Find num1 - num2 ALGORITHM STEPS 1 Calculate Total Sum Sum(1..n) = n*(n+1)/2 = 10*11/2 = 55 2 Count Divisible by m k = n/m = 10/3 = 3 Numbers: 3, 6, 9 3 Calculate num2 num2 = m*k*(k+1)/2 = 3*3*4/2 = 18 4 Calculate Result num1 = total - num2 = 37 Answer = num1 - num2 Optimal Formula: total - 2*num2 = 55 - 2*18 = 19 FINAL RESULT Calculation Breakdown num1 (Not divisible by 3) 1+2+4+5+7+8+10 = 37 num1 = 37 num2 (Divisible by 3) 3+6+9 = 18 num2 = 18 num1 - num2 37 - 18 = 19 Output: 19 Key Insight: Instead of iterating through all numbers, use the arithmetic sum formula: Sum(1..n) = n*(n+1)/2. For multiples of m up to n: there are k=n/m such numbers, and their sum = m * k * (k+1) / 2. Final answer = total_sum - 2 * sum_of_multiples. Time Complexity: O(1), Space Complexity: O(1). TutorialsPoint - Divisible and Non-divisible Sums Difference | Optimal Solution
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