Compute Sum of Divisible Integers Using Inclusion-Exclusion
Math & Bit ManipulationModel answerLast updated
Find the total of all positive integers below n divisible by 3, 5, or 7 in constant time using arithmetic series and inclusion-exclusion.
You are given a positive integer n. Your task is to compute the sum of all positive integers strictly below n that are divisible by at least one of 3, 5, or 7.
Each qualifying integer should be counted exactly once, even if it is divisible by more than one of these numbers.
Your algorithm must handle values of n up to 10^18 efficiently.
Function Signature
def compute_sum(n: int) -> int:
pass
Constraints
1 ≤ n ≤ 10^18- The output fits within standard integer types (Python handles arbitrary precision natively; other languages may require 128-bit integers or big-integer libraries)
Examples
Example 1
Input: n = 12
Output: 40
Explanation:
Integers below 12 divisible by 3, 5, or 7:
3, 5, 6, 7, 9, 10
Sum: 3 + 5 + 6 + 7 + 9 + 10 = 40
Example 2
Input: n = 20
Output: 99
Explanation:
Integers below 20 divisible by 3, 5, or 7:
3, 5, 6, 7, 9, 10, 12, 14, 15, 18
Note that 15 is divisible by both 3 and 5, but counted only once.
Sum: 3 + 5 + 6 + 7 + 9 + 10 + 12 + 14 + 15 + 18 = 99
Example 3
Input: n = 3
Output: 0
Explanation:
No positive integers strictly below 3 are divisible by 3, 5, or 7.
Notes
- The integer
nitself is not included even if it is divisible by 3, 5, or 7 (the requirement is "strictly below"). - A brute-force loop will time out for large
n. You need a closed-form solution.
Hints
Hint 1
Use the closed-form formula for summing an arithmetic sequence: multiples of k below n are k, 2k, ..., mk where m = (n-1)//k, and their sum is k·m·(m+1)/2.
Hint 2
Apply the inclusion-exclusion principle: add sums for 3, 5, and 7; subtract overlaps (15, 21, 35); then add back the triple overlap (105).
Hint 3
Remember to use integer division throughout to avoid precision loss, and be mindful of overflow for intermediate products near 10^36 in languages without arbitrary precision.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The constraint that n can reach 10^18 immediately rules out iterating through each candidate integer. Instead, we rely on two mathematical tools: the arithmetic series formula and the principle of inclusion-exclusion.
Step 1: Sum Multiples of a Single Divisor
The positive multiples of some divisor k that are strictly below n form the sequence k, 2k, 3k, ..., mk, where m = (n - 1) // k. (We use n - 1 to enforce "strictly below," so if n itself is a multiple of k, it gets excluded.)
This is an arithmetic progression with first term k, last term mk, and count m. The sum is:
S(k) = k · (1 + 2 + ... + m) = k · m · (m + 1) / 2
This formula runs in O(1) time.
Step 2: Handle Overlaps with Inclusion-Exclusion
If we naively compute S(3) + S(5) + S(7), we double-count integers divisible by two of these numbers and triple-count those divisible by all three.
The inclusion-exclusion principle corrects this:
Total = S(3) + S(5) + S(7)
− S(15) − S(21) − S(35)
+ S(105)
Here's why:
- S(15) accounts for integers divisible by both 3 and 5 (i.e., divisible by lcm(3,5) = 15).
- S(21) and S(35) similarly correct for the overlaps (3,7) and (5,7).
- S(105) restores integers divisible by all three, which were added three times, then subtracted three times, netting zero—so we add them back once.
Since 3, 5, and 7 are pairwise coprime, each least common multiple is simply the product of the divisors involved.
Step 3: Implementation Details
- Integer division only. The product
m · (m + 1)is always even, so dividing by 2 is exact. Never use floating-point division—it loses precision for large integers. - Overflow handling. For
n ≈ 10^18, intermediate products can reach around 10^36. Python's arbitrary-precision integers handle this natively. In C++ or Java, use 128-bit integers (__int128orBigInteger). - Edge cases. When
n ≤ 3, the formula naturally yields zero because(n - 1) // 3 = 0. No special-case code is needed.
Code
def compute_sum(n: int) -> int:
def sum_multiples(k: int) -> int:
# Count of multiples of k strictly below n
count = (n - 1) // k
# Sum of the arithmetic series k, 2k, ..., count*k
return k * count * (count + 1) // 2
return (
sum_multiples(3)
+ sum_multiples(5)
+ sum_multiples(7)
- sum_multiples(15)
- sum_multiples(21)
- sum_multiples(35)
+ sum_multiples(105)
)
Verification
Example 1: n = 12
- S(3): count = 3, sum = 3·3·4/2 = 18
Wait, that's wrong. Let me recalculate: multiples are 3, 6, 9, so count = 3 and sum = 3 + 6 + 9 = 18. ✓ - S(5): count = 2, sum = 5·2·3/2 = 15 (multiples: 5, 10) ✓
- S(7): count = 1, sum = 7·1·2/2 = 7 (multiple: 7) ✓
- S(15), S(21), S(35), S(105): all zero (no multiples below 12)
- Total: 18 + 15 + 7 = 40 ✓
Example 2: n = 20
- S(3) = 3·6·7/2 = 63 (multiples: 3, 6, 9, 12, 15, 18)
- S(5) = 5·3·4/2 = 30 (multiples: 5, 10, 15)
- S(7) = 7·2·3/2 = 21 (multiples: 7, 14)
- S(15) = 15·1·2/2 = 15 (multiple: 15)
- S(21), S(35), S(105): zero
- Total: 63 + 30 + 21 − 15 = 99 ✓
Complexity
- Time: O(1). Seven arithmetic evaluations, each involving a fixed number of operations.
- Space: O(1). No auxiliary data structures.
Common Mistakes
- Using
n // kinstead of(n - 1) // k. This incorrectly includesnitself whennis a multiple ofk. - Forgetting the triple-intersection term S(105). This leads to undercounting integers divisible by all three.
- Using floating-point division. For large
n, this introduces rounding errors. Always use integer division//. - Ignoring overflow. In statically typed languages without big integers, intermediate products overflow 64-bit types. Use 128-bit arithmetic or big-integer libraries.
- Not verifying against a brute-force loop for small inputs. Hand-tracing examples catches off-by-one errors early.
Extension: Arbitrary Divisor Sets
If the divisors were arbitrary (say, {4, 6, 10}), you would:
- Enumerate all non-empty subsets of the divisor set.
- For each subset, compute its least common multiple (LCM).
- Add S(LCM) if the subset size is odd; subtract if even.
When divisors are not pairwise coprime, you must use LCM instead of the product. For instance, lcm(4, 6) = 12, not 24.
For k divisors, this takes O(2^k) time, which is feasible up to about k = 20–25. Pruning strategies (stopping early when the LCM exceeds n) can improve practical performance significantly.