Sum Multiples of Three, Five, or Seven
Implement sum_multiples(limit). Return the sum of all distinct positive integers strictly less than limit that are divisible by 3, 5, or 7.
An integer divisible by more than one divisor is included only once. The limit itself is never included.
Constraints
-
0 <= limit <= 10^18
-
The result fits in a signed 64-bit integer for the supplied tests.
-
Derive an approach that does not iterate through every integer below a very large limit.
Examples
-
sum_multiples(12)
returns
40
because the included values are
3, 5, 6, 7, 9, 10
.
-
sum_multiples(3)
returns
0
.
Clarifications
Explain how overlap between divisor sets is corrected and how to sum an arithmetic progression without enumerating it.
Hints
Inclusion-exclusion applies to multiples of individual divisors, pairwise least common multiples, and the three-way least common multiple.
Extensions
-
Accept an arbitrary list of divisors.
-
Return the result modulo a positive integer.
-
Discuss overflow-safe intermediate arithmetic.