Sum Multiples - Problem

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

Return an integer denoting the sum of all numbers in the given range satisfying the constraint.

Input & Output

Example 1 — Basic Case
$ 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 2 — Smaller Range
$ 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 3 — 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 ≤ 106

Visualization

Tap to expand
Sum Multiples - Optimal Solution INPUT Range [1, n] where n = 10 1 2 3 4 5 6 7 8 9 10 Divisible by 3, 5, or 7 Not divisible Divisible numbers: 3 (div 3) 5 (div 5) 6 (div 3) 7 (div 7) 9 (div 3) 10 (div 5) n = 10 ALGORITHM STEPS 1 Initialize sum = 0 2 Loop 1 to n for i in range(1, n+1) 3 Check Divisibility if i%3==0 or i%5==0 or i%7==0 4 Add to Sum sum += i Running Sum: 0 + 3 = 3 3 + 5 = 8 8 + 6 = 14 14 + 7 = 21 21 + 9 = 30 30 + 10 = 40 FINAL RESULT Numbers included in sum: 3 5 6 7 9 10 3 + 5 + 6 + 7 + 9 + 10 = 40 OK - Output: 40 Time: O(n) Space: O(1) Key Insight: Use modulo operator (%) to check divisibility. A number is included if n%3==0 OR n%5==0 OR n%7==0. The OR condition ensures numbers divisible by multiple factors (like 15 = 3*5) are counted only once. TutorialsPoint - Sum Multiples | Optimal Solution
Asked in
Google 25 Amazon 18
24.5K Views
Medium Frequency
~15 min Avg. Time
892 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