Are the heights of binary trees [log2n]+1 and log2(n+1) equal?

\left \lfloor {log_{2}}^{n} \right \rfloor+1  Are and    \left \lceil {log_{2}}^{(n+1)} \right \rceil equal?

 For integers, the two are equal; for floating point numbers, they are not necessarily equal.

 Test code:

#include <stdio.h>
#include <math.h>
int main()
{
    long int maxnum = 100000;
    //整数测试
    for(int n = 1; n<maxnum; n++)
    {
        int down = floor(log(n)/log(2)) + 1;
        int up = ceil(log(n+1)/log(2));
        if(down != up)
            printf("down = %d,up = %d,n = %f\n",down,up,n);
    }
    printf("1到%lu之间的所有整数都满足两式相等\n",maxnum);

    //浮点数测试
    for(double n = 1; n<maxnum; n+=0.11)
    {
        int down = floor(log(n)/log(2)) + 1;
        int up = ceil(log(n+1)/log(2));
        if(down != up)
            printf("down = %d,up = %d,n = %f\n",down,up,n);
    }

    double d = 3.0;
    int b = floor(log(3.0)/log(2.0)) + 1;
    int e = ceil(log(3.0+1)/log(2.0));
    printf("\nb = %d,e = %d",b,e);

    double p = log(3.000001+1);
    double q = log(2);
    int out = ceil(p/q);
    printf("\np = %f,q = %f,out = %d",p,q,out);

    return 0;
}

In order to facilitate screenshots, the maximum value of the test is only set to 30. Readers can set a larger value for testing according to their needs, and the results should be the same. 

Attached:

 

Guess you like

Origin blog.csdn.net/quxuexi/article/details/125936856