Skip to content

Instantly share code, notes, and snippets.

@terakilobyte
Last active August 29, 2015 14:23
Show Gist options
  • Save terakilobyte/aa7b316d30af0a3063cf to your computer and use it in GitHub Desktop.
Save terakilobyte/aa7b316d30af0a3063cf to your computer and use it in GitHub Desktop.
Etudes 4dash2
defmodule Etudes4 do
@moduledoc """
Etudes chapter 4
"""
@doc """
Calculates the greatest common divisor of two integers using the Dijkstra
algorithm.
Examples:
iex> Etudes4.gcd4dash2(5, 5)
5
iex> Etudes4.gcd4dash2(136, 7)
1
iex> Etudes4.gcd4dash2(6, 12)
6
"""
@spec gcd4dash2(number(), number()) :: number()
def gcd4dash2(m, n) do
_gcd4dash2(m, n)
end
defp _gcd4dash2(m, n) when m == 0 or n == 0 do
0
end
defp _gcd4dash2(m, n) when m == n do
m
end
defp _gcd4dash2(m, n) when m > n do
_gcd4dash2(m - n, n)
end
defp _gcd4dash2(m, n) do
_gcd4dash2(m, n - m)
end
end
defmodule Etudes4Test do
use ExUnit.Case
doctest Etudes4
test "correctly calculates the gcd of even numbers" do
assert Etudes4.gcd4dash2(2, 2000000) == 2
end
test "correctly calculates the gcd of even/odd numbers" do
assert Etudes4.gcd4dash2(5, 50) == 5
end
test "handles primes correctly by returning 1" do
assert Etudes4.gcd4dash2(11, 234) == 1
end
test "handles equality" do
assert Etudes4.gcd4dash2(7,7) == 7
end
test "handles nonsensical gcds" do
assert Etudes4.gcd4dash2(0, 50) == 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment