Project Euler Problem 1
Statement
If we list all the natural numbers below that are multiples of or , we get and . The sum of these multiples is . Find the sum of all the multiples of or below .
Solution
Suppose the base numbers were and below so , they would create duplicates, ie is counted twice. Therefore take the sum of each multiple to the limit, and one time remove the numbers counted twice:
This revealed a general solution, for base numbers below :
Testing this as code:
>>> def f(n,m,L):
... a = floor((L-1)/n)
... b = floor((L-1)/m)
... c = floor((L-1)/(n*m))
... return ((n*a*(a+1)) + (m*b*(b+1)) - (n*m*c*(c+1)))/2
...
>>> f(2,3,10)
44.0
>>> f(3,5,10)
23.0This general solution passes the two tests above.
>>> f(3,5,1000)
233168.0Testing against the question, this result is successful. But what about for more than 2 numbers? How can this be approached?
Given a set of base numbers, a multiple would be counted once for each of its divisors present in .
An easy solution is that in code, a hashmap could track the number of times each number is counted, and iteratively remove duplicates.
The goal is to not add the number if it was already added.
Mathamatically this can be done piecewise. If a previous element of divides , skip that number.