Sum Multiples - Problem
Sum Multiples is a classic mathematical problem that appears frequently in coding interviews.

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 n
Output: 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
From O(n) to O(1): Mathematical OptimizationBrute ForceCheck each number1, 2, 3, 4, 5...O(n) timeOptimizeMathematicalArithmetic seriesSum = n(n+1)/2O(1) timeInclusion-Exclusion FormulaSum(3) + Sum(5) + Sum(7)- Sum(15) - Sum(21) - Sum(35)+ Sum(105)Where Sum(d) = d × (n÷d) × (n÷d + 1) ÷ 2Constant Time Solution!Example: n = 21Step 1: Sum of multiples of 3 = 3×7×8÷2 = 84Step 2: Sum of multiples of 5 = 5×4×5÷2 = 50Step 3: Sum of multiples of 7 = 7×3×4÷2 = 42Step 4: Remove overlaps - Sum(15)=15, Sum(21)=21, Sum(35)=0Step 5: Add back Sum(105) = 0Result: 84 + 50 + 42 - 15 - 21 + 0 = 140
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 10
28.5K Views
Medium Frequency
~15 min Avg. Time
850 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