We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sum Multiples

Difficulty: Easy


Problem Description

Given a positive integer n, find the sum of all integers in the range [1, n] inclusive that are divisible by 3, 5, or 7. Return an integer denoting the sum of all numbers in the given range satisfying the constraint.


Key Insights

  • To find the sum of numbers divisible by 3, 5, or 7, we can iterate through the range from 1 to n.
  • We can utilize a simple loop to check divisibility for each number.
  • Using a set can help avoid counting duplicates if a number is divisible by multiple divisors.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

The problem requires iterating through all integers from 1 to n and checking if each integer is divisible by 3, 5, or 7. We will maintain a running total of the sums of these integers. The solution can be implemented using a simple loop and conditional checks.


Code Solutions

def sum_multiples(n):
    total_sum = 0
    for i in range(1, n + 1):
        if i % 3 == 0 or i % 5 == 0 or i % 7 == 0:
            total_sum += i
    return total_sum
← Back to All Questions