add solution for problem 23
This commit is contained in:
parent
ba075f979f
commit
a557909346
1 changed files with 38 additions and 0 deletions
38
problems/23/solution.exs
Normal file
38
problems/23/solution.exs
Normal file
|
@ -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()
|
||||
|
Loading…
Add table
Reference in a new issue