0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elixir で100以下の素数を求める

Last updated at Posted at 2019-11-23

先日、akiba.ex 主催の Elixir のもくもく会に行ってきた。Elixir を久しぶりに触って興味をもったので書いてみた。

defmodule Prime do
  def is_prime_loop(n, i) when n < i * i do
    true
  end

  def is_prime_loop(n, i) do
    cond do
      rem(n, i) == 0 -> false
      true -> is_prime_loop(n, i + 2)
    end
  end

  def is_prime(n) do
    cond do
      n < 2 -> false
      n == 2 -> true
      rem(n, 2) == 0 -> false
      true -> is_prime_loop(n, 3)
    end
  end
end

Enum.each(1 .. 100, fn(i) ->
  if Prime.is_prime(i) do
    IO.puts i
  end
end)

これは習作なので、アルゴリズムの効率性は無視している(効率的な素数計算には、エラトステネスの篩というアルゴリズムを使うとよい)。

ループがないようなので、再帰で代用した。cond がスッキリしていて好き。

参考

Elixir 本家チュートリアル
Elixir 基礎文法最速マスター

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?