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?
floorit appears that you can usetruncto be more succinct. - Andrew Mortoniex(10)> :timer.tc( fn -> Integer.to_string(b_fact) |> String.length end ) {16825611, 456574}iex(11)> :timer.tc( fn -> Integer.to_char_list(b_fact) |> length end ) {16704290, 456574}- Fred the Magic Wonder Dog