Changing numerical base and other math tools/functions

I don’t immediately see how to use log, but here’s an O(1) version that is pretty fast:

function getdigit_(n::Integer, digit::Integer; base=10)
    digit < 1 && error("Digit must be positive number.")
    m = (ndigits(n; base=base) - digit + 1)
    d = divrem(n, base^(m-1))[1]
    return divrem(d, base)[2]
end

Edit: The above will fail in some cases, we must keep track of the integer type. Here’s better version, but it is still virtually untested, caveat emptor!

Also, note that it is O(1) in the selection of the digit, but not O(1) in the size of the number n.

function getdigit_(n::T, digit::Integer; base=10) where {T<:Integer}
    digit < 1 && error("Digit must be positive number.")
    m = (ndigits(n; base=base) - digit + 1)
    d = divrem(n, T(base)^(m-1))[1]
    return divrem(d, base)[2]
end

Notice for example the sign:

julia> getdigit_(-24234, 2)
-4
2 Likes