All posts

Math / Count number of digits with Logarithm

Posted On 01.21.2022

Suppose that a number n has d digits, then:

10d1n<10d

Because 10d is the smallest integer with d+1 digits.

Now, take logs base 10 of this relation:

log10(10d1)log10n<log10(10d)

This becomes:

d1log10n<d

If you now take the integer part of log10n, throwing away everything to the right of the decimal point, you will get log10n=d1. Thus, d=log10n+1.

For example, 234 is a 3 digits number, take the logs base 10:

log10(234)2.369215

If we take the integer part and throw away everything to the right of the decimal point, it’s 2.

The calculation can be done programmatically like this:

#include <math>
 
int digits = log10(n) + 1;

Source: Proof: How many digits does a number have? - StackExchange Mathematics