Sum of multiples
- O(n) · Medium
- Full plan
- Python
- JavaScript
- loops
- lists
- division
Problem
Write a function that takes two things, in this order: a list of factors and a limit. It returns the sum of the numbers below the limit that are multiples of at least one of the factors. The limit itself is left out. A number is a multiple of another one when the division comes out even: 6 is a multiple of 3 because 6 divided by 3 gives 2 and nothing is left. The numbers you look at go from 1 up to the limit, limit not included. With factors 3 and 5 and limit 4 you look at 1, 2 and 3: the only one that is a multiple of either factor is the 3, so you return 3.
Here is the part people get wrong: a number that is a multiple of several factors is added only once. With factors 4 and 6 and limit 15 the numbers that count are 4, 6, 8 and 12. The 12 is a multiple of 4 and also of 6, but it goes in once: the total is 30, not 42.
If the list of factors comes in empty, you return 0.
A factor of 0 is ignored: it adds nothing to the sum. Skip it before dividing, because in Python dividing by 0 blows up.
Examples
The example above
[3, 5], 4 → 3
Three and five up to 10
[3, 5], 10 → 23
No multiples at all
[3, 5], 1 → 0
Three factors
[7, 13, 17], 20 → 51
No factors
[], 10 → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def sum_multiples(factors, limit):
passJavaScript
function sumMultiples(factors, limit) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.