Total of Numbers Sharing a Factor of 3, 5, or 7
Math & Bit ManipulationAuto-graded · 21 test casesLast updated
Compute the sum of integers from 1 to n divisible by at least one of 3, 5, or 7, counting each integer once, which tests overlap handling and inclusive bounds.
You are given a positive integer n. Consider every whole number from 1 up to and including n. Call a number eligible if it can be divided evenly by at least one of 3, 5, or 7.
Return the sum of all eligible numbers.
Rules
- The range is inclusive on both ends, so
nitself is considered. - A number that is divisible by several of the three divisors (for example
15,21,35, or105) contributes to the sum only once. - If no number in the range is eligible, return
0.
Constraints
1 <= n <= 1000- The result is at most 500,500, so it fits comfortably in a 32-bit signed integer.
Examples
Example 1
Input: sum_eligible(21)
Output: 140
Example 2
Input: sum_eligible(2)
Output: 0
Example 3
Input: sum_eligible(12)
Output: 52
Hints
Hint 1
Think about each number from 1 to n separately: ask a single yes/no question about whether it is divisible by 3, 5, or 7.
Hint 2
If you test divisibility with a combined 'or' condition, a number like 15 passes the test once and is added once, so no extra correction is needed.
Hint 3
Make sure the loop includes n itself, and remember that an empty selection should give 0. For a faster alternative, arithmetic series sums combined with inclusion-exclusion also work.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through every integer k from 1 to n inclusive. If k is divisible by 3, by 5, or by 7, add it to a running total. Return the total.
The check is a single combined condition: k % 3 == 0 or k % 5 == 0 or k % 7 == 0. Because it is one true/false test per number, a value such as 15 (divisible by both 3 and 5) passes once and is added once. No separate correction for overlaps is required.
Why it is correct
- Coverage:
range(1, n + 1)yields exactly the integers in[1, n], includingn. - Selection: a number is added precisely when it is a multiple of at least one of 3, 5, or 7, which is the definition of eligible.
- No double counting: each number is visited once and contributes either itself or nothing.
- Empty case: when nothing qualifies (e.g.
n = 1orn = 2), the sum of an empty sequence is0.
Complexity
- Time: O(n), with at most three modulo checks per number.
- Space: O(1), since the generator produces values lazily.
Optional faster approach
For very large n, use arithmetic series with inclusion-exclusion. The sum of multiples of d up to n is d * m * (m + 1) / 2 where m = n // d. Then:
S(3) + S(5) + S(7) - S(15) - S(21) - S(35) + S(105)
This runs in O(1) time. It works because 3, 5, and 7 are pairwise coprime, so each combined divisor is simply their product.
Reference solution
def sum_eligible(n: int) -> int:
return sum(k for k in range(1, n + 1) if k % 3 == 0 or k % 5 == 0 or k % 7 == 0)