Skip to content

Instantly share code, notes, and snippets.

@stevemolloy
Last active December 13, 2021 18:26
Show Gist options
  • Save stevemolloy/64ff06327c5a9f72297a82e061b15460 to your computer and use it in GitHub Desktop.
Save stevemolloy/64ff06327c5a9f72297a82e061b15460 to your computer and use it in GitHub Desktop.
Prime numbers in Elixir
defmodule Numbers do
def prime?(2), do: :true
def prime?(num) do
last = num
|> :math.sqrt
|> Float.ceil
|> trunc
notprime = 2..last
|> Enum.any?(fn a -> rem(num, a)==0 end)
!notprime
end
def nextprime(num) do
cond do
prime?(num + 1) -> num + 1
true -> nextprime(num + 1)
end
end
def nthprime(n) do
Stream.iterate(2, &nextprime/1)
|> Enum.at(n-1)
end
def divisors(num) do
do_divisors(num, 1)
end
defp do_divisors(num, n) do
cond do
prime?(num) -> [num]
rem(num, nthprime(n))==0 ->
[nthprime(n) |
do_divisors(trunc(num/nthprime(n)), n)]
true -> do_divisors(num, n+1)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment