A more mathematical way to solve the first problem in the project Euler archives.

87 Views Asked by At

Okay so the problem itself is really simple,

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 3 or 5 below 1000.

Many people will just solve this using a for loop and and the modulo operator like this,

s = 0
for x in range(1000):
  if x % 3 == 0 or x % 5 == 0:
    s += x
print(s)

But I felt the need to solve it using just mathemathics and came up with this: Let $s$ be the sum, $n=10$ and $x_1 = 3, x_2=5$. We have,

$$ \newcommand\c[1]{\left\lceil#1\right\rceil} \newcommand\p[1]{\left(#1\right)} \newcommand\ep{\varepsilon} $$

\begin{align*} s &= (3 + 6 + 9) + (5) \\ &= x_1(1 + 2 + 3) + x_2(1) \\ &= x_1\sum_{i=1}^{m_1}i + x_2\sum_{i=1}^{m_2}i && m_i = \c{\frac{n}{x_i}}-1 \\ &= x_1\frac{m_1(m_1+1)}{2} + x_2\frac{m_2(m_2+1)}{2} \\ &= x_1\frac{\p{\c{\frac{n}{x_1}}-1}\c{\frac{n}{x_1}}}{2} + x_2\frac{\p{\c{\frac{n}{x_2}}-1}\c{\frac{n}{x_2}}}{2} \\ &= \sum_{i}\p{x_i\frac{\p{\c{\frac{n}{x_i}}-1}\c{\frac{n}{x_i}}}{2}} \end{align*}

At this point, we have over summed since $x_1, x_2$ may share multiples. So if they are relatively prime, we can write:

$$ s = \sum_{i}\p{x_i\frac{\p{\c{\frac{n}{x_i}}-1}\c{\frac{n}{x_i}}}{2}} - \ep $$

where $\ep = x_3\frac{\p{\c{\frac{n}{x_3}}-1}\c{\frac{n}{x_3}}}{2}$ for $x_3 = x_1x_2$. But now the issue is the assumption that $x_i$'s are relatively prime or there is only two of them. Consider a more general case where $x_i \in X \supset \mathbb{N}$ and $x_i < n \in \mathbb{N}$. Is there an elegant way to state $\ep$ in this case? I feel like I need to use LCM somehow but can't quite think how.


Example. Let $X = \{2,3,9\}$ and $n = 10$. We have:

\begin{align*} 2&:\{2,4,6,8\} \\ 3&:\{3,6,9\} \\ 9&:\{9\} \end{align*}

Now, we need a way to count (or have the same effect thereof) the 6 and 9 only once.