KatInterview

Total of Numbers Sharing a Factor of 3, 5, or 7

Math & Bit ManipulationAuto-graded · 21 test cases
EasyAuto-gradedMath & Bit Manipulationmathinclusion-exclusioniteration

Last 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 n itself is considered.
  • A number that is divisible by several of the three divisors (for example 15, 21, 35, or 105) 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.