Program to compute Log n in C

CServer Side ProgrammingProgramming

Given with the value of n as an input and the task is to compute the value of Log n through a function and display it.

Logarithm or Log is the inverse function to exponentiation which means to calculate log the raised power must be calculated as a base.

IF

  $$\log_b x\;\:=\: y\:than\:b^{y}=x$$

Like

 $$\log_2 64\;\:=\: 6\:than\:2^{6}=64$$

Example

Input-: Log 20
Output-: 4
Input-: Log 64
Output-: 6

Algorithm

Start
In function unsigned int log2n(unsigned int num)
   Step 1-> Return (num > 1) ? 1 + log2n(num / 2) : 0
In function int main()
   Step 1-> Declare and assign num = 20
   Print log2n(num)
Stop

Example

 Live Demo

#include <stdio.h>
//We will be using recursive Approach used below is as follows
unsigned int log2n(unsigned int num) {
   return (num > 1) ? 1 + log2n(num / 2) : 0;
}
int main() {
   unsigned int num = 20;
   printf("%u\n", log2n(num));
   return 0;
}

Output

4
raja
Published on 18-Oct-2019 13:01:24
Advertisements