Elixir Count Non Divisible
defmodule CountNonDivisible do
def count_non_divisible(a) do
size = length(a)
occurrences = Enum.frequencies(a)
Enum.map(a, fn v -> size - divisor_occurrences(1, v, occurrences, 0) end)
end
defp divisor_occurrences(i, v, _occurrences, count) when i * i > v, do: count
defp divisor_occurrences(i, v, occurrences, count) do
count =
if rem(v, i) == 0 do
count = count + Map.get(occurrences, i, 0)
if div(v, i) != i do
count + Map.get(occurrences, div(v, i), 0)
else
count
end
else
count
end
divisor_occurrences(i + 1, v, occurrences, count)
end
end
This counts how often each value appears, then subtracts the divisor matches so you get the non-divisible count for each item.