Skip to main content
Back to problems
Leetcode
Easy
Math
Number Theory
Divisible And Non Divisible Sums Difference

Compute the difference between the sum of numbers from 1 to n that are not divisible by m and the sum of numbers that are divisible by m.

Acceptance 100%
Problem Statement

Problem

Given two integers n and m, consider all integers from 1 to n inclusive.

  • Let A be the sum of all numbers in this range that are not divisible by m.
  • Let B be the sum of all numbers in this range that are divisible by m.

Return A - B.

You should compute the result for the given pair (n, m).

Notes

  • A number x is divisible by m if x % m == 0.
  • The range always starts at 1 and ends at n.

Input Format

  • Two integers n and m.

Output Format

  • Return an integer representing A - B.

Constraints

  • 1 <= n
  • 1 <= m
  • Use the problem's input bounds as given by the platform when implementing.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 10, m = 3

Output

19

Explanation

Numbers not divisible by 3 are 1, 2, 4, 5, 7, 8, 10, whose sum is 37. Numbers divisible by 3 are 3, 6, 9, whose sum is 18. The difference is 37 - 18 = 19.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.