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.
This problem is really simple and I want to learn more about Julia (e.g. passing arguments). Hence, I built a more generalized version:
#=
# This is a generalized version of Project Euler problem 1
#
# The generalized problem can be described as: Σnᵢ where n∈N mod d∈D == 0. The default values are the ones from the original problem:
#
# Inputs:
# N := highest positive integer (natural number) of which we check if Divisors are a multiple; default N := 999
# Divisors := Array of integers that should be tested as multiples; default Divisors := [3;5]
# Output:
# Sum of all numbers n∈N, where n mod d∈D == 0
#
=#
function checkIfMultiplesOf(n::UInt64, Divisors::Array{UInt64,1})
for d in Divisors
if mod(n,d) == 0
return n
end
end
return 0
end
function ProjectEuler0001(N::UInt64, Divisors::Array{UInt64,1})
totalSum = 0;
for n in 1:1:N
totalSum += checkIfMultiplesOf(n, Divisors)
end
println(totalSum);
end
function checkARGS()
Divisors = Array{UInt64,1}();
if isempty(ARGS) == false
N = tryparse(UInt64,ARGS[1])
for i in split(ARGS[2], ",")
push!(Divisors,tryparse(UInt64,i))
end
else
N::UInt64 = 999;
push!(Divisors,0x3);
push!(Divisors,0x5);
end
return N, Divisors
end
function main()
N, Divisors = checkARGS()
ProjectEuler0001(N, Divisors)
end
main()
Let’s try it out:
$ julia ProjectEuler0001.jl
233168
$ julia ProjectEuler0001.jl 17361 3,7,13
71227391
I’m not using a proper argument handling such as ArgParse.jl. Further, I assume that either none or both inputs are given.