Program to compute Log n
Write a one line C function that calculates and returns
. For example, if n = 64, then your function should return 6, and if n = 129, then your function should return 7.
Using Recursion
C
// 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; } |
Java
// 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 |
Python3
# 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 = 32print(Log2n(n)) # This code is contributed by # Smitha Dinesh Semwal |
C#
// 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. |




where k can be any anything, which for standard log functions are either e or 10