Friday, 2 December 2011

log2( x ): Binary Logarithm

In the math.h of Turbo C, binary logarithm ( log2( ) ) doesn't exists. When we are working with tree, we need to calculate depth of the tree, as well as the number of nodes in that depth.
The number of nodes in ith depth can be calculated using : 2i . formula
the max number of node in ith depth : n = 2i - 1 (complete tree).
You can use these formula to find the number of nodes in particular depth.

On the other hand, you may need to find the depth you are currently in.
There is a very easy way to do that. This is using binary logarithm to find the current depth.

...
#include <math.h>
double log2(double x)
{
       return log(x) / log(2);
}

If i made mistakes let me know
Good luck

No comments:

Post a Comment