CS 61A

Structure and Interpretation of Computer Programs, Spring 2015

Instructor: John DeNero




Question | Sum of all Multiples

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of M or N below some number LIMIT.

def sum_multiples(m, n, limit):
    """
    >>> sum_multiples(3, 5, 10)
    23
    >>> sum_multiples(3, 7, 1000)
    214216
    """
    ## YOUR CODE HERE ##
def sum_multiples(m, n, limit):
    count = 0
    total = 0
    while count < limit:
        if count % m == 0:
            total += count
        elif count % n == 0:
            total += count
        count += 1
    return total