Multiples of 3 or 5

Author

Angel Alcala Ruiz

Published

November 20, 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.

Solution

Let’s solve using Julia

Code
function SumOfMultiples(n)

#' @@name SumOfMultiples 
#'
#' @@description
#'
#' This function finds the sum of all the natural numbers below n that are multiples of 3 or 5
#'
#' @@arg n: A positive integer n
#'
#' @@return The sum of all the natural numbers below n that are multiples of 3 or 5
#'
#' @@examples
#'
#' n = 10
#' SumOfMultiples(n)

    sum_of_multiples = 0
    for i = 1:(n - 1)
        if (i%3 == 0) || (i%5 == 0)
            sum_of_multiples = sum_of_multiples + i
        end
    end
    return sum_of_multiples
end
SumOfMultiples (generic function with 1 method)

We can check the sum of all the multiples that are below 10

Code
SumOfMultiples(10)
23

Now we can check the sum of all the multiples that are 1000

Code
SumOfMultiples(1000)
233168