From a5579093468eeaad610e59e0aded5be3a7cccb93 Mon Sep 17 00:00:00 2001 From: Caleb Webber Date: Sat, 1 Mar 2025 21:48:42 -0500 Subject: [PATCH] add solution for problem 23 --- problems/23/solution.exs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 problems/23/solution.exs diff --git a/problems/23/solution.exs b/problems/23/solution.exs new file mode 100644 index 0000000..0d11334 --- /dev/null +++ b/problems/23/solution.exs @@ -0,0 +1,38 @@ +defmodule AmicableNumbers do + def divisors(n) do + [ 1 | + (for i <- 2..floor(:math.sqrt(n))//1, + j = div(n, i), + j == n / i do + if i !== j, do: [i,j], else: [i] + end |> Enum.flat_map(&(&1))) ] + end +end + +defmodule Abundance do + def is_abundant?(n) do + cache = Process.get(:abundance, %{}) + + case cache |> Map.get(n) do + nil -> + sum = AmicableNumbers.divisors(n) |> Enum.sum() + is? = sum > n + Process.put(:abundance, Map.put(cache, n, is?)) + is? + is? -> is? + end + end +end + +# sum of all numbers that can be expressed as sum of two abundant numbers +sum = for n <- 1..28123, + mid = div(n, 2), + Enum.any?(1..mid, &(Abundance.is_abundant?(&1) and Abundance.is_abundant?(n - &1))), + reduce: 0 + do + s -> s + n +end + +(((28123*28124)/2) - sum) +|> IO.puts() +