DEV Community

Discussion on: Daily Challenge #78 - Number of Proper Fractions with Denominator d

Collapse
 
brightone profile image
Oleksii Filonenko

Elixir:

defmodule Day78 do
  @spec proper_fractions(pos_integer) :: non_neg_integer
  def proper_fractions(1), do: 0
  def proper_fractions(denom) when denom > 1 do
    Enum.count(1..denom, &(Integer.gcd(&1, denom) == 1))
  end
end

Tests:

defmodule Day78Test do
  use ExUnit.Case
  import Day78, only: [proper_fractions: 1]

  test "1/1 is improper" do
    assert proper_fractions(1) == 0
  end

  test "2/1 is proper" do
    assert proper_fractions(2) == 1
  end

  test "other common cases" do
    assert proper_fractions(5) == 4
    assert proper_fractions(15) == 8
    assert proper_fractions(25) == 20
  end

  test "works only with positive numbers" do
    assert_raise FunctionClauseError, fn -> proper_fractions(0) end
    assert_raise FunctionClauseError, fn -> proper_fractions(-1) end
  end
end