Published: March 28, 2023

Project Euler

Problem 1 - Multiples of 3 and 5

Problem

This problem comes from Project Euler 1

Problem

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.

Solution

We have to find all the multiples of 3 or 5 below 1000 and get the sum. One thing to be careful of are multiples of 15, as they are multiples of both 3 and 5, and we want multiples of 3 or 5.

We avoid the above problem by checking if a number is divisible by either 3 or 5, and thus we only list each number divisible by 3 or 5 once. In the code below, we check to see if any number is a multiple of three first, and if it isn’t, we check to see if it is a multiple of 5.

Code

# Project Euler: Problem 1
# Multiples of 3 or 5

sum = 0
for number in range (3, 1000):
    # if number is divisible by 3 or 5
    if (number % 3 == 0 or number % 5 == 0):
        sum += number

print(sum)
// Project Euler: Problem 1
// Multiples of 3 or 5
// Alternate Rust version

fn main() {
    let mut sum = 0;
    for number in 3..1000 {
        if number % 3 == 0 || number % 5 == 0 {
            sum += number;
        }
    }

    println!("{}", sum);
}