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

Number: 2752

Difficulty: Easy

Paid? No

Companies: Yahoo


Problem Description

Given a positive integer n, compute the sum of all integers within the range [1, n] (inclusive) that are divisible by 3, 5, or 7.


Key Insights

  • We need to iterate through every number in the range from 1 to n.
  • Check divisibility by 3, 5, or 7 for each number.
  • Sum the numbers that meet the criteria.
  • The constraints allow a simple linear solution since n is at most 10^3.

Space and Time Complexity

Time Complexity: O(n) - We iterate once through the numbers from 1 to n. Space Complexity: O(1) - Only a few variables are used regardless of the input size.


Solution

The solution utilizes a simple loop that iterates from 1 to n and checks each number for divisibility by 3, 5, or 7 using the modulo operator. If a number is found to be divisible by any of these, it is added to the cumulative sum. This approach leverages basic arithmetic operations and conditional checks, which is efficient given the problem constraints.


Code Solutions

# Function to calculate the sum of multiples of 3, 5, or 7 from 1 to n
def sumMultiples(n):
    # Initialize total sum to zero
    total_sum = 0
    # Iterate through each number from 1 to n (inclusive)
    for number in range(1, n + 1):
        # Check if the number is divisible by 3, 5, or 7
        if number % 3 == 0 or number % 5 == 0 or number % 7 == 0:
            # Add the number to the total sum if divisible
            total_sum += number
    # Return the computed total sum
    return total_sum

# Example usage:
# n = 10 should return 40
print(sumMultiples(10))
← Back to All Questions