Calculate Logn in one line

Write a one line C function that calculates and returns \log_2 n. For example, if n = 64, then your function should return 6, and if n = 129, then your function should return 7.

Using Recursion

// C program to find log(n) using Recursion
#include<stdio.h>

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;
}
Output
5

Time complexity: O(log n)
Auxiliary space: O(log n) if the stack size is considered during recursion otherwise O(1)

Using inbuilt log function


We can use the inbuilt function of standard library which is available in library.

// C program to find log(n) using Inbuilt 
// function of <math.h> library
#include<stdio.h>
#include<math.h>
int main()
{
  unsigned int n = 32;
  printf("%d", (int)log2(n) );
  return 0;
}
Output
5

Time complexity: O(1)
Auxiliary space: O(1)

Let us try an extended version of the problem.

Write a one line function Logn(n ,r) which returns \lfloor\log_r n\rfloor.

Using Recursion

// C program to find log(n) on arbitrary base using Recursion
#include<stdio.h>

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 = 3;
  printf("%u", Logn(n, r));
  return 0;
}
Output
5

Time complexity: O(log n)
Auxiliary space: O(log n) if the stack size is considered during recursion otherwise O(1)

Using inbuilt log function


We only need to use logarithm property to find the value of log(n) on arbitrary base r. i.e., \log_r n = \dfrac{log_k (n)}{\log_k (r)} where k can be any anything, which for standard log functions are either e or 10

// C program to find log(n) on arbitrary base
// using log() function of maths library
#include<stdio.h>
#include<math.h>

unsigned int Logn(unsigned int n, unsigned int r)
{
   return log(n) / log(r);
}

int main()
{
  unsigned int n = 256;
  unsigned int r = 3;
  printf("%u", Logn(n, r));

  return 0;
}
Output
5

Time complexity: O(1)
Auxiliary space: O(1)
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.