Katkat

Sum of Integers Up to n Divisible by 3, 5, or 7

AbridgeSoftware Engineer · Online Assessment

Last updated

From an Abridge online assessment: given a positive integer n, return the sum of all integers from 1 to n that are divisible by 3, 5 or 7, adding numbers such as 15 or 21 only once. It tests precise handling of overlapping divisibility conditions and inclusive range boundaries.

Given a positive integer n, return the sum of every integer in the range [1, n] that is divisible by at least one of 3, 5 or 7.

Function Signature

def sum_multiples(n: int) -> int:

Rules

  • Both ends of the range are included.
  • An integer divisible by more than one of 3, 5 and 7 (such as 15 or 21) is added only once.
  • If no integer in the range qualifies, return 0.

Constraints

  • 1 <= n <= 1000
  • The answer is at most 500,500, so it fits in a 32-bit signed integer.

Examples

Example 1

Input: n = 21
Output: 140

The qualifying integers are 3, 5, 6, 7, 9, 10, 12, 14, 15, 18, 20 and 21. Both 15 and 21 have two of the divisors but are added once each.

Example 2

Input: n = 2
Output: 0

Neither 1 nor 2 is divisible by 3, 5 or 7.

Example 3

Input: n = 12
Output: 52

The qualifying integers are 3, 5, 6, 7, 9, 10 and 12.