Elixir Common Prime Divisors
defmodule CommonPrimeDivisors do
def common_prime_divisors(a, b) do
a
|> Enum.zip(b)
|> Enum.count(fn {x, y} ->
d = gcd(x, y)
remove_common(x, d) == 1 and remove_common(y, d) == 1
end)
end
defp gcd(n, m) when rem(n, m) == 0, do: m
defp gcd(n, m), do: gcd(m, rem(n, m))
defp remove_common(1, _m), do: 1
defp remove_common(n, m) do
d = gcd(n, m)
if d == 1, do: n, else: remove_common(div(n, d), m)
end
end
This checks whether two numbers are built from the same prime factors by repeatedly dividing out their shared parts.