3
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 で ユークリッドの互除法

Last updated at Posted at 2019-08-27

ユークリッドの互除法:剰余算の結果を用いて剰余算のループをすることで最大公約数を求められるアルゴリズム

Input

x y

OutPut

GCD(x, y)

Info

  • x > y であれば GCD(x, y) = GCD(x - y, y)
  • x = y であれば GCD(x, y) = x

を使って計算量をさげてます

Code

defmodule GCD do
  def gcd(x, 0), do: x
  def gcd(0, y), do: y
  def gcd(x, y) do
    cond do
      x > y -> gcd(x - y, y)
      x == y -> x
      true -> gcd(x, rem(y, x))
    end
  end
end

[a, b] = IO.gets("") |> String.split(" ")
  |> Enum.map(&(String.trim(&1) |> String.to_integer))

IO.puts(Gcd.gcd(a, b))

所感

一部冗長な気もしますがやっぱりコードが見やすいのでElixir好きです

3
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
3
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?