Product of consecutive Fib numbers - how to cache?

FYI:


Spoiler
defmodule ProdFib do
  def product_fib(n),
    do: product_fib(n,0,1)

  defp product_fib(n, f_m, f_n) do
    product = f_m * f_n
    cond do
      product < n ->
        product_fib(n, f_n, f_m + f_n)
      product > n ->
        [f_m, f_n, false]
      true ->
        [f_m, f_n, true]
    end
  end
end

IO.inspect ProdFib.product_fib(714) # [21, 34, true]
IO.inspect ProdFib.product_fib(800) # [34, 55, false]
IO.inspect ProdFib.product_fib(4895) # [55, 89, true]
IO.inspect ProdFib.product_fib(5895) # [89, 144, false]
IO.inspect ProdFib.product_fib(74049690) # [6765, 10946, true]
IO.inspect ProdFib.product_fib(2563195080744681828) # [1836311903, 2971215073, false]
1 Like