Project Euler: solution to problem 001
Jorge Martínez Garrido
March 14, 2023
Problem 1
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.
Mathematical background
The multiple of a number is defined such that:
$$ b = n \cdot a $$
In previous expression:
- The integer number $a$ is named the divisor.
- The integer number $b$ is named the multiple.
- The integer number $n$ is named the multiplier.
The modulus and the remainder are not the same!
Let us clarify the difference between modulus and remainder. These two mathematical concepts are not the same. In addition, they are treated differently by different programming languages.
There are plenty of posts explaining this concept all over the web. However, let me explain here the difference using my own words and diagrams.
Remainder
At school, we are taught the “Euclidean division” as one of the basic arithmetic operations. For example, if we split a cake into 9 pieces and there are a total of 4 people, each people receives two slices. This implies 1 slice is left over, this means that it remains in the table without being consumed.
Remember that the Euclid’s division lemma is defined as:
$$ b = aq + r $$
In previous expression:
- The integer $b$ is the divident.
- The integer $a$ is the divisor.
- The integer $q$ is the quotient.
- The integer $r$ is the remainder.
Note that when $r=0$, then $q \equiv n$.
Modulus
The modulus can be defined as the particular value within modular arithmetic for which the system wraps around itself, starting again.
The modulus operation is widely used in criptography due to its “one way function” and in computer graphics for creating the feeling of an infinite game board, as in the Asteroids game.
Possible origin of the confusion
Due to its applications, the modulus operator usually involves dealing with positive integer values. In this situation, the result of the modulus operation is the same as the one for the remainder.
Solution
The solution is presented in three different languages: C, Rust and Python. Note
that two constants named LOWER_BOUND
and UPPER_BOUND
have been defined so
this code can be extended on demand.
Also, note that we are using in all the cases the modulo
operator. However,
because all the quantities involved are unsigned integers, its result is the
same as the one for the remainder
.
Output
Answer: 233168