Sum Multiples

Given a positive integer `n`, find the sum of all integers in the range `[1, n]` that are divisible by `3`, `5`, or `7`. Return that sum.

30:00

Sum Multiples
easy
Free written solution
Topics
Companies

Given a positive integer n, find the sum of all integers in the range [1, n] that are divisible by 3, 5, or 7.

Return that sum.

Example 1:
Input: {"n":7}
Output: 21
Constraints:
  • 1≤n≤1031 \leq n \leq 10^3

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":7}

f(k) sums the multiples of k up to 7: k + 2k + ... + mk = k * m(m + 1) / 2 with m = n // k. Adding f(3), f(5), f(7) alone would count shared multiples twice.

1..7, times each number is counted

once

twice

3 times

1
2
3
4
5
6
7

+ f(3)

?

+ f(5)

?

+ f(7)

?

- f(15)

?

- f(21)

?

- f(35)

?

+ f(105)

?

total

0

Variables
VariableValue
n7
total0
DepthFunction Call
Stack empty
0/8