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 (1 and n both 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, or 105).
  • Return 0 whenever [1, n] contains no multiples of 3, 5, or 7.

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

  1. 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 by 3, 5, or 7:

    • Both endpoints 1 and n participate (so n = 10 includes 10 itself, and n = 35 includes 35).
    • Any integer divisible by two or all three of {3, 5, 7} — such as 15 (3 and 5), 21 (3 and 7), 35 (5 and 7), or 105 (all three) — must be counted once.
    • When [1, n] contains no qualifying multiples (such as n = 1 or n = 2), return 0.
  2. Baseline first: scan `1..n` with an `or` check

    With n <= 1000, checking each integer from 1 to n in a plain loop takes at most 1000 steps. Combining the three remainder checks with or naturally 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 total
    

    In a timed assessment, this O(n) loop is quick and reliable — and makes a great reference test. Next, let's derive the O(1) closed-form formula that interviewers expect when they ask, "What if n is 10^12?"

  3. Sum the multiples of one divisor in `O(1)` time

    Take a single divisor divisor (say 3 with limit = 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 // divisor multiples (0 when limit < divisor), and factoring out divisor leaves 1 + 2 + ... + count. Writing that sum forward and backward pairs every column to count + 1:

      S =  1     +   2       + ... + count
    + S =  count + (count-1) + ... + 1
    ---------------------------------------------------
     2S = (count + 1) + (count + 1) + ... + (count + 1)   (count pairs)
      S = count * (count + 1) // 2
    

    Because count and count + 1 are consecutive integers, one of them is always even, so integer division // 2 is 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_sum
    
  4. Fix overlaps with inclusion-exclusion

    If we only compute S(3) + S(5) + S(7) (writing S(k) for sum_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 a and b? Exactly the multiples of their least common multiple (LCM) — the smallest positive integer divisible by both a and b. Because 3, 5, and 7 are prime numbers (they share no common factors above 1), 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 4 and 6, you would use lcm(4, 6) = 12, never 4 * 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     |    1
    

    Every qualifying integer ends up counted once!

  5. 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 = 342
    

    Notice that 101 = 15 + 30 + 21 + 35 — the exact four numbers in [1, 35] that were counted twice in single_sums! For Example 1 (n = 10), single_sums = 18 + 15 + 7 = 40 and all overlap sums are 0, giving 40. For Example 2 (n = 1), 1 // k == 0 for every divisor k, returning 0 cleanly with no special-case if needed.

  6. 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 call sum_of_multiples_of exactly 7 times, and each call performs a fixed handful of integer multiplications and divisions regardless of how large n is (for arbitrarily huge multi-digit Python integers, arithmetic scales only with the number of digits O(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 = 1 or n = 2, Example 2): n // divisor evaluates to 0 for all seven divisors, returning 0 naturally with no special if branches.
  • Upper boundary n itself is a multiple (n = 10 in Example 1, or n = 3, 5, 7, 15, 35, 105): Floor division n // divisor includes n when divisor divides n evenly, matching the inclusive [1, n] rule.
  • Multiples of two divisors (15, 21, 30, 35 in Example 3): Added twice in single_sums and subtracted once in pair_sums, contributing to the final sum once.
  • Multiples of all three divisors (n = 105): Added 3 times in single_sums, subtracted 3 times in pair_sums, and added back once in triple_sum, raising the sum from n = 104 (2940) to n = 105 (3045) by 105.
  • Top of constraint (n = 1000): Evaluates to 272066, comfortably inside a 32-bit signed integer.

Common mistakes

  • Forgetting inclusion-exclusion (S(3) + S(5) + S(7)): Double-counts 15, 21, 35 and triple-counts 105.
  • Subtracting pairs but forgetting + S(105): Completely drops 105, 210, ..., 945 (3 - 3 = 0 times counted) whenever n >= 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 of lcm(4, 6) = 12, not 4 * 6 = 24.
  • Using floating-point division / instead of integer division //: In Python, / produces a 64-bit float, which loses integer precision once sums exceed 2^53 (~9 * 10^15). Always use //.
  • Off-by-one upper bound: Writing (n - 1) // divisor (a habit from "strictly below n" problems) wrongly excludes n itself when n is divisible by 3, 5, or 7.

Alternative approaches

  • Direct O(n) single-pass loop: Loop for i in range(1, n + 1): and add i when i % 3 == 0 or i % 5 == 0 or i % 7 == 0. For n <= 1000 this runs in microseconds and handles any number of divisors without subset math, though it cannot scale to huge n.

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. Python int expands to arbitrary precision automatically (sum_multiples(10**12) == 271428571428928571428569), whereas signed 64-bit integers (int64_t / i64, max ~9.22 * 10^18) overflow inside S(3) once n exceeds ~5.26 * 10^9, requiring 128-bit integers (__int128 in C++ or i128 in Rust) and dividing the even factor in count vs count + 1 by 2 before multiplying.
  • How would you generalize the calculation to an arbitrary list of k divisors that might not be pairwise coprime? Enumerate all 2^k - 1 non-empty subsets of the divisor list (via recursion or a bitmask 1 .. (1 << k) - 1), compute each subset's exact L = math.lcm(*subset) rather than its raw product, and add sum_of_multiples_of(L, n) for odd-sized subsets while subtracting it for even-sized subsets. Pruning recursive branches as soon as L > n (where n // L == 0) keeps small-to-moderate k (k <= 20) fast; if k is large and n is moderate, a boolean sieve of length n + 1 is 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 from 1 through x (defining sum_multiples(0) = 0), and return sum_multiples(right) - sum_multiples(left - 1). Every qualifying multiple below left cancels out, leaving the exact sum across [left, right] in O(1) time.

Follow-up questions

Similar questions

More Abridge interview questions

All 4 Abridge questions →