tvl-depot/assessments/semiprimes/server/lib/server.ex
William Carroll 45877a8b9c Include cache hit/miss info in return type
This can be useful downstream for diagnostics.
2020-12-12 02:43:35 +00:00

33 lines
564 B
Elixir

defmodule Server do
@moduledoc """
Documentation for `Server`.
"""
@doc """
If `n` contains exactly two prime factors, return those prime factors;
otherwise, return nothing.
"""
def semiprime(n) do
case Cache.get(n) do
nil ->
case do_semiprime(n) do
nil ->
nil
res ->
Cache.put(n, res)
{:miss, res}
end
hit ->
{:hit, hit}
end
end
defp do_semiprime(n) do
case Math.factor(n) do
[_, _] = res -> res
_ -> nil
end
end
end