Sha256: 35acf26e0244c7ef3942d14983343c68fc2f6529ce8a684da77df59d3383cdfd

Contents?: true

Size: 1.17 KB

Versions: 195

Compression:

Stored size: 1.17 KB

Contents

defmodule PerfectNumbers do
  @doc """
  Determine the aliquot sum of the given `number`, by summing all the factors
  of `number`, aside from `number` itself.

  Based on this sum, classify the number as:

  :perfect if the aliquot sum is equal to `number`
  :abundant if the aliquot sum is greater than `number`
  :deficient if the aliquot sum is less than `number`
  """
  @spec classify(number :: integer) :: ({ :ok, atom } | { :error, String.t() })
  def classify(number) when number < 1, do: { :error, "Classification is only possible for natural numbers." }
  def classify(number) do
    { :ok, number |> aliquot_sum |> do_classify(number) }
  end

  defp do_classify(aliquot, aliquot), do: :perfect
  defp do_classify(aliquot, number) when aliquot > number, do: :abundant
  defp do_classify(_, _), do: :deficient

  defp aliquot_sum(number) do
    number
    |> factors
    |> Enum.reject(&(&1 == number))
    |> Enum.sum
  end

  defp factors(number), do: factors(number, div(number, 2))
  defp factors(1, _), do: [1]
  defp factors(_, 1), do: [1]
  defp factors(number, i) when rem(number, i) == 0, do: [i | factors(number, i-1)]
  defp factors(number, i), do: factors(number, i-1)
end

Version data entries

195 entries across 195 versions & 1 rubygems

Version Path
trackler-2.2.1.49 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.48 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.47 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.46 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.45 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.44 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.43 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.42 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.41 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.40 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.39 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.38 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.37 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.36 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.35 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.34 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.33 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.32 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.31 tracks/elixir/exercises/perfect-numbers/example.exs
trackler-2.2.1.30 tracks/elixir/exercises/perfect-numbers/example.exs