Program to compute Log n in C

In C programming, computing the logarithm base 2 of a number n can be achieved using recursive or iterative approaches. The logarithm function determines the power to which a base must be raised to obtain a given number.

The mathematical relationship is: if logb x = y, then by = x

For example: log2 64 = 6, because 26 = 64

Syntax

unsigned int log2n(unsigned int num);

Method 1: Using Recursive Approach

This method uses recursion to divide the number by 2 until it becomes 1 or less −

#include <stdio.h>

unsigned int log2n(unsigned int num) {
    return (num > 1) ? 1 + log2n(num / 2) : 0;
}

int main() {
    unsigned int num1 = 20;
    unsigned int num2 = 64;
    
    printf("Log base 2 of %u = %u<br>", num1, log2n(num1));
    printf("Log base 2 of %u = %u<br>", num2, log2n(num2));
    
    return 0;
}
Log base 2 of 20 = 4
Log base 2 of 64 = 6

Method 2: Using Iterative Approach

This approach uses a loop to count how many times we can divide the number by 2 −

#include <stdio.h>

unsigned int log2n_iterative(unsigned int num) {
    unsigned int count = 0;
    while (num > 1) {
        num /= 2;
        count++;
    }
    return count;
}

int main() {
    unsigned int num = 32;
    
    printf("Log base 2 of %u = %u<br>", num, log2n_iterative(num));
    
    return 0;
}
Log base 2 of 32 = 5

How It Works

  • Recursive Method: Divides the number by 2 and adds 1 to the count until the number becomes 1 or less
  • Iterative Method: Uses a while loop to repeatedly divide by 2 and increment a counter
  • Both methods calculate floor(log2(n)) for positive integers

Conclusion

Computing log base 2 in C can be done efficiently using either recursive or iterative approaches. The recursive method is more elegant but uses call stack memory, while the iterative approach is memory-efficient for large numbers.

Updated on: 2026-03-15T12:16:26+05:30

612 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements