2018-1-18

Finding the sum of all multiples of 3 or 5 below 1000 with OCaml

The easiest way to find all the multiples of 3 or 5 below 1000 with Ocaml is to use a recursive function with a switch.

The first Project Euler problem - Multiples of 3 and 5 - is stated as follows. Find the sum of all the multiples of 3 or 5 below 1000.

(* Recursive switch *)
let multiples target =
  let rec next x sum =
    match (x mod 3 = 0 || x mod 5 = 0, x > 0) with
    | (false, true) -> next (x - 1) sum
    | (true, true) -> next (x - 1) (sum + x)
    | _ -> sum in
  next (target - 1) 0
(* Recursive switch + one function argument  *)
let multiples target =
  let rec next sum =
    function
    | 0 -> sum
    | n when n mod 3 = 0 || n mod 5 = 0 -> next (sum + n) (n - 1)
    | n -> next sum (n - 1) in
  next 0 target
Jan Järfalk — User experienced esthete, technician, geek and web worker. Aspiring artist and recreational mathematician. I indulge and travel plenty. Constraints are good.