How can we effectively count numbers in general in Elixir?

How can we efficiently count numbers in integers in Elixir?

My attempt at Iex

iex(1)> a=100_000                                               
100000
iex(2)> Enum.reduce(1..a, &(&1*&2))|> to_string|> String.length
456574
iex(3)> 

      

Makes over 15 seconds

Another implementation:

defmodule Demo do
    def cnt(n), do: _cnt(n,0)
    defp _cnt(0,a), do: a
    defp _cnt(n,a),do: _cnt(div(n,10),a+1)
end

      

Is slower: b = 100_000!

Suggestion for comments (thanks Fred!)

iex> Integer.to_char_list(b) |> length

      

Best so far and simplest

IEx> :timer.tc(fn -> Demo.cnt b  end)
{277662000, 456574}
IEx> :timer.tc(fn ->b |> to_string |> String.length end) 
{29170000, 456574}

      

Is there a built-in wizardry for this in any Elixir module?

+3


source to share


1 answer


Elixir 1.1 and up now has a built-in function

Integer.digits/2

      



This handles counting digits efficiently

-1


source







All Articles