about summary refs log tree commit diff
path: root/assessments/semiprimes/server/lib/server.ex
blob: 7ab5e905b5a062956dff4117d1bee2c08a4e2303 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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