Sum of 3, 5, and 7 Multiples Within [1, n]
Hard · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given an integer n >= 1, compute the total of all integers x satisfying 1 <= x <= n that are evenly divisible by 3, 5, or 7.
Implement sum_multiples(n):
def sum_multiples(n: int) -> int:
Follow these rules:
- Treat the interval
[1, n]as closed on both ends (1andnboth participate if divisible). - Count each qualifying integer at most once, even when two or all three of
{3, 5, 7}divide it without remainder (for instance,15,21,35, or105). - Return
0whenever[1, n]contains no multiples of3,5, or7.
Examples
Example 1
Input: n = 10
Output: 40
Within [1, 10], the multiples of 3, 5, or 7 are 3, 5, 6, 7, 9, 10 (including the upper bound 10), which add up to 40.
Example 2
Input: n = 1
Output: 0
Because 1 leaves a non-zero remainder when divided by 3, 5, and 7, no value qualifies and the sum is 0.
Example 3
Input: n = 35
Output: 342
Every multiple of 3, 5, or 7 up through 35 is included, while numbers with two matching divisors—15, 21, 30, and 35—contribute to the sum once each, giving 342.
Constraints
1 <= n <= 1000- The returned sum fits within a standard 32-bit signed integer.
Step-by-step walkthrough
Understand the interval and the single-count rule
Given a positive integer
n, we need the sum of all integers in[1, n]that are evenly divisible by3,5, or7:- Both endpoints
1andnparticipate (son = 10includes10itself, andn = 35includes35). - Any integer divisible by two or all three of
{3, 5, 7}— such as15(3and5),21(3and7),35(5and7), or105(all three) — must be counted once. - When
[1, n]contains no qualifying multiples (such asn = 1orn = 2), return0.
- Both endpoints
Baseline first: scan `1..n` with an `or` check
With
n <= 1000, checking each integer from1tonin a plain loop takes at most1000steps. Combining the three remainder checks withornaturally adds each qualifying number once, even if two or three divisors match:def brute_sum_multiples(n: int) -> int: total = 0 for i in range(1, n + 1): if i % 3 == 0 or i % 5 == 0 or i % 7 == 0: total += i return totalIn a timed assessment, this
O(n)loop is quick and reliable — and makes a great reference test. Next, let's derive theO(1)closed-form formula that interviewers expect when they ask, "What ifnis10^12?"Sum the multiples of one divisor in `O(1)` time
Take a single divisor
divisor(say3withlimit = 18). Its multiples in[1, limit]are:3, 6, 9, 12, 15, 18 -> count = 18 // 3 = 6 multiples = 3 * (1 + 2 + 3 + 4 + 5 + 6)In general, there are
count = limit // divisormultiples (0whenlimit < divisor), and factoring outdivisorleaves1 + 2 + ... + count. Writing that sum forward and backward pairs every column tocount + 1:S = 1 + 2 + ... + count + S = count + (count-1) + ... + 1 --------------------------------------------------- 2S = (count + 1) + (count + 1) + ... + (count + 1) (count pairs) S = count * (count + 1) // 2Because
countandcount + 1are consecutive integers, one of them is always even, so integer division// 2is always exact with zero remainder:def sum_of_multiples_of(divisor: int, limit: int) -> int: """Return the sum of all multiples of `divisor` in the inclusive range [1, limit].""" count = limit // divisor triangular_sum = count * (count + 1) // 2 return divisor * triangular_sumFix overlaps with inclusion-exclusion
If we only compute
S(3) + S(5) + S(7)(writingS(k)forsum_of_multiples_of(k, n)), any number divisible by two of{3, 5, 7}gets added twice, and any number divisible by all three gets added three times.Which numbers are divisible by both
aandb? Exactly the multiples of their least common multiple (LCM) — the smallest positive integer divisible by bothaandb. Because3,5, and7are prime numbers (they share no common factors above1), each group's LCM is simply its product:- Pairwise LCMs:
lcm(3, 5) = 15,lcm(3, 7) = 21,lcm(5, 7) = 35 - Three-way LCM:
lcm(3, 5, 7) = 105
(Caution: if divisors shared a factor, such as
4and6, you would uselcm(4, 6) = 12, never4 * 6 = 24.)By the inclusion-exclusion principle, we add the single-divisor sums, subtract the pairwise-LCM sums, and add back the three-way-LCM sum:
answer = (S(3) + S(5) + S(7)) - (S(15) + S(21) + S(35)) + S(105) Verify how many times each kind of qualifying number is counted: Number | Divisible by | + Singles | - Pairs | + Triple | Net count -------+---------------+-----------+---------+----------+---------- 6 | {3} | +1 | 0 | 0 | 1 15 | {3, 5} | +2 | -1 | 0 | 1 105 | {3, 5, 7} | +3 | -3 | +1 | 1Every qualifying integer ends up counted once!
- Pairwise LCMs:
Trace Example 3 (`n = 35`), Example 1 (`n = 10`), and Example 2 (`n = 1`)
Let's plug
n = 35(Example 3) into all seven terms:divisor | count = 35 // divisor | S(divisor) = divisor * count * (count + 1) // 2 --------+-----------------------+------------------------------------------------ 3 | 35 // 3 = 11 | 3 * 11 * 12 // 2 = 198 5 | 35 // 5 = 7 | 5 * 7 * 8 // 2 = 140 7 | 35 // 7 = 5 | 7 * 5 * 6 // 2 = 105 -> single_sums = 443 15 | 35 // 15 = 2 | 15 * 2 * 3 // 2 = 45 21 | 35 // 21 = 1 | 21 * 1 * 2 // 2 = 21 35 | 35 // 35 = 1 | 35 * 1 * 2 // 2 = 35 -> pair_sums = 101 105 | 35 // 105 = 0 | 0 -> triple_sum = 0 Result = 443 - 101 + 0 = 342Notice that
101 = 15 + 30 + 21 + 35— the exact four numbers in[1, 35]that were counted twice insingle_sums! For Example 1 (n = 10),single_sums = 18 + 15 + 7 = 40and all overlap sums are0, giving40. For Example 2 (n = 1),1 // k == 0for every divisork, returning0cleanly with no special-caseifneeded.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def sum_of_multiples_of(divisor: int, limit: int) -> int: """Return the sum of all multiples of `divisor` in the inclusive range [1, limit].""" # Number of multiples: divisor, 2*divisor, ..., count*divisor (0 if limit < divisor). count = limit // divisor # 1 + 2 + ... + count = count * (count + 1) // 2. # Integer division // 2 is always exact because count and count + 1 are consecutive, # so one of them is guaranteed to be even. triangular_sum = count * (count + 1) // 2 return divisor * triangular_sum def sum_multiples(n: int) -> int: # Phase 1: Add multiples of each single divisor (3, 5, and 7). single_sums = ( sum_of_multiples_of(3, n) + sum_of_multiples_of(5, n) + sum_of_multiples_of(7, n) ) # Phase 2: Subtract multiples of each pairwise LCM (15 = 3*5, 21 = 3*7, 35 = 5*7), # because numbers divisible by two divisors were added twice in Phase 1. pair_sums = ( sum_of_multiples_of(15, n) + sum_of_multiples_of(21, n) + sum_of_multiples_of(35, n) ) # Phase 3: Add back multiples of the three-way LCM (105 = 3*5*7). # They were added 3 times in Phase 1 and subtracted 3 times in Phase 2 (net 0 so far). triple_sum = sum_of_multiples_of(105, n) return single_sums - pair_sums + triple_sum✅ Submit now — all tests should pass.
Intuition & how it works
Imagine adding up membership dues across three school clubs — the 3s club, the 5s club, and the 7s club — where some students belong to two or even all three clubs, yet each student should pay dues only once. First, the multiples of any single divisor k up to n (k, 2k, ..., count * k, where count = n // k) form an arithmetic progression (a sequence of numbers with a constant step between neighbors), so we can add all of them instantly as k * count * (count + 1) // 2. Second, we combine the three clubs using the inclusion-exclusion principle (a counting rule that adds individual group totals, subtracts two-way overlaps, and adds back three-way overlaps so every shared element is counted once), using each overlap's least common multiple (LCM) (the smallest positive integer divisible by every number in a group): 15, 21, 35 for pairs, and 105 for all three.
Why do the naive approaches fall short? Looping through every integer from 1 to n with if i % 3 == 0 or i % 5 == 0 or i % 7 == 0 works for n <= 1000, but takes O(n) time and grinds to a halt if an interviewer scales n up to 10^9 or 10^12. Conversely, if you use the closed-form progression formula for 3, 5, and 7 and simply return S(3) + S(5) + S(7), you double-count numbers like 15, 21, and 35 and triple-count 105. Worse yet, if you subtract the pairs S(15) + S(21) + S(35) and stop there, multiples of 105 are added 3 times and subtracted 3 times (3 - 3 = 0), vanishing from the sum completely!
Let's trace Example 3 (n = 35, true sum = 342), where 15, 30, 21, and 35 belong to two divisors each:
1. Single divisors:
S(3) = 3 * (11 * 12 // 2) = 198
S(5) = 5 * (7 * 8 // 2) = 140
S(7) = 7 * (5 * 6 // 2) = 105
single_sums = 198 + 140 + 105 = 443 (double-counts 15, 30, 21, and 35)
2. Pairwise overlaps (LCMs 15, 21, 35):
S(15) = 15 + 30 = 45, S(21) = 21, S(35) = 35 -> pair_sums = 101
3. Three-way overlap (LCM 105):
S(105) = 0 -> triple_sum = 0
Answer = 443 - 101 + 0 = 342
Complexity
- Time:
O(1). We callsum_of_multiples_ofexactly7times, and each call performs a fixed handful of integer multiplications and divisions regardless of how largenis (for arbitrarily huge multi-digit Python integers, arithmetic scales only with the number of digitsO(log n)). - Space:
O(1). Only a constant number of integer variables (count,triangular_sum,single_sums,pair_sums,triple_sum) are stored in memory.
Edge cases
- No qualifying multiples (
n = 1orn = 2, Example 2):n // divisorevaluates to0for all seven divisors, returning0naturally with no specialifbranches. - Upper boundary
nitself is a multiple (n = 10in Example 1, orn = 3, 5, 7, 15, 35, 105): Floor divisionn // divisorincludesnwhendivisordividesnevenly, matching the inclusive[1, n]rule. - Multiples of two divisors (
15, 21, 30, 35in Example 3): Added twice insingle_sumsand subtracted once inpair_sums, contributing to the final sum once. - Multiples of all three divisors (
n = 105): Added3times insingle_sums, subtracted3times inpair_sums, and added back once intriple_sum, raising the sum fromn = 104(2940) ton = 105(3045) by105. - Top of constraint (
n = 1000): Evaluates to272066, comfortably inside a 32-bit signed integer.
Common mistakes
- Forgetting inclusion-exclusion (
S(3) + S(5) + S(7)): Double-counts15, 21, 35and triple-counts105. - Subtracting pairs but forgetting
+ S(105): Completely drops105, 210, ..., 945(3 - 3 = 0times counted) whenevern >= 105. - Multiplying non-coprime divisors instead of taking
lcm: For{3, 5, 7}the product equals the LCM because all three are distinct primes, but if an interviewer changes the divisors to{4, 6}, numbers divisible by both are multiples oflcm(4, 6) = 12, not4 * 6 = 24. - Using floating-point division
/instead of integer division//: In Python,/produces a64-bitfloat, which loses integer precision once sums exceed2^53(~9 * 10^15). Always use//. - Off-by-one upper bound: Writing
(n - 1) // divisor(a habit from "strictly belown" problems) wrongly excludesnitself whennis divisible by3,5, or7.
Alternative approaches
- Direct
O(n)single-pass loop: Loopfor i in range(1, n + 1):and addiwheni % 3 == 0 or i % 5 == 0 or i % 7 == 0. Forn <= 1000this runs in microseconds and handles any number of divisors without subset math, though it cannot scale to hugen.
Follow-up questions
- How does this solution behave when n grows to 10^12 or beyond, and what integer-width pitfalls arise in fixed-width languages like C++ or Rust? The
7-term inclusion-exclusion formula still finishes in constant time while a linear loop would take hours. Pythonintexpands to arbitrary precision automatically (sum_multiples(10**12) == 271428571428928571428569), whereas signed 64-bit integers (int64_t/i64, max~9.22 * 10^18) overflow insideS(3)oncenexceeds~5.26 * 10^9, requiring128-bit integers (__int128in C++ ori128in Rust) and dividing the even factor incountvscount + 1by2before multiplying. - How would you generalize the calculation to an arbitrary list of k divisors that might not be pairwise coprime? Enumerate all
2^k - 1non-empty subsets of the divisor list (via recursion or a bitmask1 .. (1 << k) - 1), compute each subset's exactL = math.lcm(*subset)rather than its raw product, and addsum_of_multiples_of(L, n)for odd-sized subsets while subtracting it for even-sized subsets. Pruning recursive branches as soon asL > n(wheren // L == 0) keeps small-to-moderatek(k <= 20) fast; ifkis large andnis moderate, a boolean sieve of lengthn + 1is faster. - How can you reuse sum_multiples to answer range queries over an arbitrary closed interval [left, right] in O(1) time? Treat
sum_multiples(x)as a prefix sum from1throughx(definingsum_multiples(0) = 0), and returnsum_multiples(right) - sum_multiples(left - 1). Every qualifying multiple belowleftcancels out, leaving the exact sum across[left, right]inO(1)time.
Follow-up questions
- How does this solution behave when n grows to 10^12 or beyond, and what integer-width pitfalls arise in fixed-width languages like C++ or Rust?
- How would you generalize the calculation to an arbitrary list of k divisors that might not be pairwise coprime?
- How can you reuse sum_multiples to answer range queries over an arbitrary closed interval [left, right] in O(1) time?
Similar questions
- Nested Bracket-Count String Decoder
- In-Place Run-Length Encoding of Character Arrays
- HIPAA-Compliant Clinical Audio Transcription Pipeline
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses