How can we efficiently count the digits in an integer in Elixir?

1.9k views Asked by At

How can we efficiently count the digits in an integer in Elixir?

My attempt in Iex

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

Takes 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 way slower: b = 100_000!

A suggestion from the comments (Thanks Fred!)

iex> Integer.to_char_list(b) |> length

Is 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 built in wizardry for this in any Elixir module?

1

There are 1 answers

1
Charles Okwuagwu On BEST ANSWER

From Elixir 1.1 and above there is now a built in feature

Integer.digits/2

This effectively handles digit counting