Katkat

Sum Multiples of Three, Five, or Seven

UpstartSoftware Engineer · Online Assessment

Last updated

Calculate the sum of all unique positive integers strictly less than a given limit that are divisible by 3, 5, or 7. The problem requires using the Principle of Inclusion-Exclusion to achieve an O(1) time complexity capable of handling inputs up to 10^18.

Problem Statement

Given a positive integer n, calculate the sum of all distinct positive integers strictly less than n that are divisible by 3, 5, or 7.

Because n can be as large as 10^18, an iterative approach checking each number will exceed the time limit. Your solution should run in O(1) time.

Function Signature

def sum_multiples(n: int) -> int:
    pass

Constraints

  • 1 <= n <= 10^18
  • The return value fits within standard arbitrary-precision integers (in Python) or requires 128-bit integer handling in languages like C++/Java.

Examples

Example 1:

Input: n = 12
Output: 40
Explanation:
The positive integers strictly less than 12 divisible by 3, 5, or 7 are:
- Multiples of 3: 3, 6, 9
- Multiples of 5: 5, 10
- Multiples of 7: 7
No number is repeated among these. Sum = 3 + 6 + 9 + 5 + 10 + 7 = 40.
Note that 12 is excluded because the integers must be strictly less than n.

Example 2:

Input: n = 20
Output: 119
Explanation:
Distinct multiples below 20:
- Divisible by 3: 3, 6, 9, 12, 15, 18
- Divisible by 5: 5, 10, 15
- Divisible by 7: 7, 14
The value 15 appears in both the 3 and 5 lists and must be counted only once.
Sum = 3 + 5 + 6 + 7 + 9 + 10 + 12 + 14 + 15 + 18 = 119.

Edge Cases to Consider

  • n <= 3: There are no positive integers strictly less than n divisible by 3, 5, or 7, so the result should be 0.
  • Exact multiples of 3, 5, or 7: Ensure n itself is not included in the sum when n is divisible by one of the divisors.

Hints

Hint 1

The sum of all multiples of k strictly less than n can be computed in O(1) time using arithmetic progression: k * m * (m + 1) // 2, where m = (n - 1) // k.

Hint 2

Applying the sum formula separately for 3, 5, and 7 double-counts numbers divisible by both (e.g., 15) and triple-counts numbers divisible by all three (105).

Hint 3

Use the Principle of Inclusion-Exclusion: Add sums for {3, 5, 7}, subtract sums for pairwise least common multiples {15, 21, 35}, and add back the sum for the triple LCM {105}.

Follow-up questions

  • How would you generalize this algorithm if the divisors were an arbitrary list of k coprime or non-coprime integers?
  • If the problem required returning the answer modulo 10^9 + 7 to prevent integer overflow in languages without native big integer support, how would modular division (modular inverse) be applied?
  • What is the time complexity of the generalized approach with k divisors, and at what value of k would an alternate algorithm (like bitmask dynamic programming or sieve-based approaches) become preferable?