Wednesday, August 17, 2011

Calculate Logn in one line

Source

Write a one line C function that calculates and returns \lfloor\log _2 \left( n \right)\rfloor. For example, if n = 64, then your function should return 6, and if n = 129, then your function should return 7.

Following is a solution using recursion.

#include
unsigned int Log2n(unsigned int n)
{
return (n > 1)? 1 + Log2n(n/2): 0;
}
int main()
{
unsigned int n = 32;
printf("%u", Log2n(n));
getchar();
return 0;
}

Let us try an extended verision of the problem. Write a one line function Logn(n ,r) which returns \lfloor\log _r \left( n \right)\rfloor. Following is the solution for the extended problem.

#include
unsigned int Logn(unsigned int n, unsigned int r)
{
return (n > r-1)? 1 + Logn(n/r, r): 0;
}
int main()
{
unsigned int n = 256;
unsigned int r = 4;
printf("%u", Logn(n, r));
getchar();
return 0;
}

No comments:

Post a Comment