KatInterview

Compute Sum of Divisible Integers Using Inclusion-Exclusion

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationinclusion-exclusionarithmetic-seriesnumber-theory

Last 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 n itself 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.