Is it safe to calculate the number of digits in an integer N
in base
b
using logarithmic functions?
No absolutely not, due to rounding errors. Specifically, the risk is that log(N)/log(b)
will be slightly less than the exact value. This is most likely to occur when N
is an exact multiple of b
.
How does one count the number of digits in an integer N
in base b
?
Divide N
by b
in a loop until N
is zero. See the countDigits
function in the code below. Handling values of N <= 0
is left as an exercise for the reader.
For example, consider the following code
int countDigits( int N, int b )
{
int count;
for ( count = 0; N; count++ )
N /= b;
return count;
}
int main( void )
{
int N, b;
if ( scanf( "%d %d", &N, &b ) != 2 )
return 1;
printf( "log(%3d) = %.50lf\n", N, log(N) );
printf( "log(%3d) = %.50lf\n", b, log(b) );
printf( "ratio = %.50lf\n", log(N)/log(b) );
printf( "expected = %d\n", countDigits(N, b) );
double digits = 1 + floor(log(N) / log(b));
printf( "computed = %lf\n", digits );
}
If the user enters 243 for N, and 3 for b, the output is
log(243) = 5.49306144334054824440727315959520637989044189453125
log( 3) = 1.09861228866810978210821758693782612681388854980469
ratio = 4.99999999999999911182158029987476766109466552734375
expected = 6
computed = 5.000000
The expected number of digits is 6 since 24310 = 1000003. The problem with the logarithm method is that either log(243)
is slightly too small or log(3)
is slightly too large, resulting in a ratio that is just below 5
when it should be exactly 5
.