Program to compute Log n

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find log(n)
// using Recursion
class Gfg1 
{
  
    static int Log2n(int n)
    {
        return (n > 1) ? 1 + Log2n(n / 2) : 0;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        int n = 32;
        System.out.println(Log2n(n));
    }
}
  
// This code is contributed by Niraj_Pandey

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to
# find log(n) using Recursion
  
def Log2n(n):
  
    return 1 + Log2n(n / 2) if (n > 1) else 0
  
# Driver code
n = 32
print(Log2n(n))
  
# This code is contributed by
# Smitha Dinesh Semwal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find log(n)
// using Recursion
using System;
  
class GFG {
  
    static int Log2n(int n)
    {
        return (n > 1) ? 1 + 
            Log2n(n / 2) : 0;
    }
      
    // Driver Code
    public static void Main()
    {
        int n = 32;
          
        Console.Write(Log2n(n));
    }
}
  
// This code is contributed by
// nitin mittal.

chevron_right