C:使用对数函数安全地计算基数 (b) 的整数 (N) 的位数

C: Safe to Calculate Number of Digits in Integer (N) of Base (b) Using Logarithmic Functions

给定公式:

NUM_DIGITS_IN_N_FOR_BASE_B = 1 + floor(ln(abs(N)) / ln(b))

这样 b 是 2 到 36 之间的基数,N 是 int 类型。

据此 post it seems okay to assume that the value returned for the range of all integers [INT_MIN, INT_MAX] would work with no round-off or overflow error. I am a bit skeptical about this. My skepticism comes from a recent post of mine @post 2。如果在计算机程序中使用数学定义不是 "safe",是否有另一个技巧可用于计算给定基数 b 的数字 N 中的位数?

Is it safe to calculate the number of digits in an integer N in base b using logarithmic functions?

不完全不是,由于舍入误差。具体来说,风险是 log(N)/log(b) 会略小于精确值。当 Nb.

的整数倍时,最有可能发生这种情况

How does one count the number of digits in an integer N in base b?

在循环中将 N 除以 b,直到 N 为零。请参阅下面代码中的 countDigits 函数。 N <= 0 的处理值留作 reader.

的练习

例如,考虑以下代码

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 );
}

如果用户为 N 输入 243,为 b 输入 3,则输出为

log(243) = 5.49306144334054824440727315959520637989044189453125
log(  3) = 1.09861228866810978210821758693782612681388854980469
ratio    = 4.99999999999999911182158029987476766109466552734375
expected = 6
computed = 5.000000

由于 24310 = 1000003,因此预期位数为 6。对数法的问题是 log(243) 稍微太小或 log(3) 稍微太大,导致比率刚好低于 5 而应该正好是 5.

第一部分回答得好post。

第二部分:

is there another trick to use to compute the number of digits in a number N given a base b.?

// Works for all `N` including `0`, `INT_MIN`
int num_digs = 1;
int T = N;
while (T /= b) num_digs++;

这将计算 位数 的数量。不计算符号字符。