Let \(N\) be an integer such that,
\[ N = c_0 + c_1 b^1 + c_2 b^2 + \cdots + c_{n-1} b^{n-1} + c_n b^n \,.\]We need to write a function, \(f(N)\), such that the argument \(N \in \mathbb{Z}\) maps to \(n+1 \in \mathbb{N}\).
function countdigits(x::Integer)
digit_len = 1
k = 10
while x % k != x
digit_len += 1
k *= 10
end
digit_len
end
@btime countdigits(x)
> 21.450 ns (0 allocations: 0 bytes)
function countdigitsrec(x::Integer)
x = div(x, 10)
x == 0 && return 1
return 1 + countdigitsrec(x)
end
@btime countdigitsrec(x)
> 17.590 ns (0 allocations: 0 bytes)
function countdigitscomp(x::Integer)
(log10(x) + 1) |> floor |> Int
end
@btime countdigitscomp(x)
> 34.696 ns (0 allocations: 0 bytes)
In Julia, the recursive implementation appears to offer the best execution time.