2018-1-18

Find the sum of all even Fibonacci numbers below four million with OCaml

The sum of all even Fibonacci numbers below four million is easily found with a recursive function and a switch.

The second Project Euler problem - Even Fibonacci Numbers - is stated as follows - By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

let fib target =
  let rec next x y sum =
    match (y mod 2 == 0, y < target) with
    | (true, true) -> next y (x + y) (sum + y)
    | (false,true) -> next y (x + y) sum
    | _ -> sum in
  next 1 1 0

let _ = print_int (fib 4000000)
Jan Järfalk — User experienced esthete, technician, geek and web worker. Aspiring artist and recreational mathematician. I indulge and travel plenty. Constraints are good.