Last active
July 7, 2016 20:00
-
-
Save radik909/9ad2593fc60760ad0d0a3be1ff134c2e to your computer and use it in GitHub Desktop.
Elixir - Problems Solving - Prime number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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