Sum Multiples - Problem
Sum Multiples is a classic mathematical problem that appears frequently in coding interviews.
You're given a positive integer
For example, if
Goal: Return an integer representing the sum of all valid numbers.
Input: A positive integer
Output: The sum of all multiples of 3, 5, or 7 in range [1, n]
You're given a positive integer
n, and your task is to find the sum of all integers in the range [1, n] inclusive that are divisible by at least one of these numbers: 3, 5, or 7.For example, if
n = 10, the numbers divisible by 3, 5, or 7 are: 3, 5, 6, 7, 9, 10. Their sum is 3 + 5 + 6 + 7 + 9 + 10 = 40.Goal: Return an integer representing the sum of all valid numbers.
Input: A positive integer
nOutput: The sum of all multiples of 3, 5, or 7 in range [1, n]
Input & Output
example_1.py — Basic Case
$
Input:
n = 7
›
Output:
21
💡 Note:
Numbers divisible by 3, 5, or 7 in range [1,7]: 3, 5, 6, 7. Sum = 3 + 5 + 6 + 7 = 21
example_2.py — Larger Range
$
Input:
n = 10
›
Output:
40
💡 Note:
Numbers divisible by 3, 5, or 7 in range [1,10]: 3, 5, 6, 7, 9, 10. Sum = 3 + 5 + 6 + 7 + 9 + 10 = 40
example_3.py — Edge Case
$
Input:
n = 3
›
Output:
3
💡 Note:
Only number 3 is divisible by 3, 5, or 7 in range [1,3]. Sum = 3
Constraints
- 1 ≤ n ≤ 109
- n is a positive integer
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
Recognize that we need multiples of 3, 5, or 7
2
Apply Set Theory
Use inclusion-exclusion to handle overlapping multiples
3
Use Arithmetic Series
Calculate sums with formula: n×(n+1)÷2 for sequence 1,2,3...n
4
Achieve O(1)
Replace iteration with direct mathematical calculation
Key Takeaway
🎯 Key Insight: Mathematical formulas can replace iterative algorithms, transforming O(n) problems into O(1) solutions using principles like inclusion-exclusion and arithmetic series.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code