log2() function in C++ with Examples

The function log2() of cmath header file in C++ is used to find the logarithmic value with base 2 of the passed argument.

Syntax:

log2(x)

Parameters: This function takes a value x, in the range [0, ∞] whose log value is to be found.

Return Type: It returns the logarithmic value, as double, float or long double type, based on the following conditions:

  • If x > 1: It returns the positive logarithmic value of x.
  • If x is equals to 1: It returns 0.
  • If 0 < x < 1: It returns the negative logarithmic value of x.
  • If x is equals to 0: It returns the negative infinity(-∞).
  • If x < 0: It returns NaN(Not a Number).

Below examples demonstrate the use of log2() method:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate log2() function
  
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    long b = 16;
    float c = 2.5;
    double d = 10.35;
    long double e = 25.5;
  
    // Logarithmic value of long datatype
    cout << log2(b) << "\n";
  
    // Logarithmic value of float datatype
    cout << log2(c) << "\n";
  
    // Logarithmic value of double datatype
    cout << log2(d) << "\n";
  
    // Logarithmic value of long double datatype
    cout << log2(e) << "\n";
  
    return 0;
}

chevron_right


Output:

4
1.32193
3.37156
4.67243

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate log2() function
  
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    // To show extreme cases
    int a = 0;
    int b = -16;
  
    // Logarithmic value of 0
    cout << log2(a) << "\n";
  
    // Logarithmic value of negative value
    cout << log2(b) << "\n";
  
    return 0;
}

chevron_right


Output:

-inf
nan

Reference: http://www.cplusplus.com/reference/cmath/log2/

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.