Skip to content

Instantly share code, notes, and snippets.

@radik909
Last active July 7, 2016 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radik909/9ad2593fc60760ad0d0a3be1ff134c2e to your computer and use it in GitHub Desktop.
Save radik909/9ad2593fc60760ad0d0a3be1ff134c2e to your computer and use it in GitHub Desktop.
Elixir - Problems Solving - Prime number
defmodule Prime do
@moduledoc """
A number 'n' is prime only when it is not divisible by any number between 2 and √n
"""
def run(2), do: true
def run(num) when num > 2 and rem(num, 2) != 0 do
is_prime(3, num, round(:math.sqrt(num) + 1))
end
def run(_), do: false
defp is_prime(start, _, stop) when start >= stop, do: true
defp is_prime(start, num, stop) do
if rem(num, start) == 0, do: false, else: is_prime(start + 2, num, stop)
end
end
IO.gets("Enter the number: ")
|> String.strip
|> String.to_integer
|> Prime.run
|> case do
true -> IO.puts "Prime number"
false -> IO.puts "Not prime number"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment