Are there more convenient ways of getting the number of digits of a positive integer? I want to define nth power of 10 for a positive integer. Say for 43 it would be 2, for 5 it would be 1, for 9999 it would be 4. As for 1, 10, 100, ... I am still shifting between two options. 10 would result either 1 or 2. But for simplicity I select it to be 2. In other words I want to get the number of digits of a positive integer with proper mathematical notation. So far I have managed to do it with log and round: (log_(10)(43))+1=2 I'm just not sure if this is good approach. As a bonus it would be nice to have a solution working with any base, not just 10.

djo57bgfrqn

djo57bgfrqn

Answered question

2022-10-28

Are there more convenient ways of getting the number of digits of a positive integer?
I want to define nth power of 10 for a positive integer. Say for 43 it would be 2, for 5 it would be 1, for 9999 it would be 4. As for 1, 10, 100, ... I am still shifting between two options. 10 would result either 1 or 2. But for simplicity I select it to be 2.
In other words I want to get the number of digits of a positive integer with proper mathematical notation.
So far I have managed to do it with log and round:
floor ( log 10 ( 43 ) ) + 1 = 2
I'm just not sure if this is good approach. As a bonus it would be nice to have a solution working with any base, not just 10.

Answer & Explanation

Finnegan Stone

Finnegan Stone

Beginner2022-10-29Added 11 answers

I'm not sure what you find inconvenient; given any natural number b 2, the number of base- b digits of a given natural number n is exactly equal to
log b ( n ) + 1
That's because, if
n = ( d k d k 1 d 1 d 0 ) b = d k b k + d k 1 b k 1 + + d 1 b + d 0
where each digit d i satisfies 0 d i b 1 and d k 0, we have
b k n < b k + 1
and because the logarithm is convex, this implies
k log b ( n ) < k + 1
so that log b ( n ) = k, and therefore log b ( n ) + 1 = k + 1, which is indeed the number of digits in the base b expansion of n

Do you have a similar question?

Recalculate according to your conditions!

Ask your question.
Get an expert answer.

Let our experts help you. Answer in as fast as 15 minutes.

Didn't find what you were looking for?