euler_ex/problems/21/solution.exs

24 lines
415 B
Elixir

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
ns = for i <- 1..10_000, into: %{} do
{i, AmicableNumbers.divisors(i) |> Enum.sum()}
end
for {a, b} <- ns,
a != b,
ns[b] == a,
reduce: 0
do
acc -> a + acc
end
|> IO.puts()