Highest power of 2 less than or equal to given number

Given a number n, find the highest power of 2 that is smaller than or equal to n.

Examples :

Input : n = 10
Output : 8

Input : n = 19
Output : 16

Input : n = 32
Output : 32

A simple solution is to start checking from n and keep decrementing until we find a power of 2.

C++



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find highest power of 2 smaller
// than or equal to n.
#include<bits/stdc++.h>
using namespace std;
  
int highestPowerof2(int n)
{
    int res = 0;
    for (int i=n; i>=1; i--)
    {
        // If i is a power of 2
        if ((i & (i-1)) == 0)
        {
            res = i;
            break;
        }
    }
    return res;
}
  
// Driver code
int main()
{
    int n = 10;
    cout << highestPowerof2(n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to find highest power 
// of 2 smaller than or equal to n.
class GFG 
{
   static int highestPowerof2(int n)
   {
     int res = 0;
     for (int i = n; i >= 1; i--)
        {
         // If i is a power of 2
          if ((i & (i - 1)) == 0)
             {
                  res = i;
                break;
             }
        }
     return res;
   }
  
   // Driver code
   public static void main(String[] args)
   {
      int n = 10;
      System.out.println(highestPowerof2(n));
   }
}
// This code is contributed by prerna saini. 
  

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find highest 
# power of 2 smaller than or 
# equal to n.
def highestPowerof2(n):
  
    res = 0;
    for i in range(n, 0, -1):
          
        # If i is a power of 2
        if ((i & (i - 1)) == 0):
          
            res = i;
            break;
          
    return res;
  
# Driver code
n = 10;
print(highestPowerof2(n));
      
# This code is contributed by mits

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to find highest power 
// of 2 smaller than or equal to n.
using System;
  
class GFG
{
public static int highestPowerof2(int n)
{
    int res = 0;
    for (int i = n; i >= 1; i--)
        {
        // If i is a power of 2
        if ((i & (i - 1)) == 0)
            {
                res = i;
                break;
            }
        }
    return res;
}
      
    // Driver Code
    static public void Main ()
    {
        int n = 10;
        Console.WriteLine(highestPowerof2(n));
    }
}
  
// This code is contributed by ajit

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find highest 
// power of 2 smaller than or 
// equal to n.
function highestPowerof2($n)
{
    $res = 0;
    for ($i = $n; $i >= 1; $i--)
    {
        // If i is a power of 2
        if (($i & ($i - 1)) == 0)
        {
            $res = $i;
            break;
        }
    }
    return $res;
}
  
// Driver code
$n = 10;
echo highestPowerof2($n);
      
// This code is contributed by m_kit
?>

chevron_right



Output :

8

Time complexity : O(n). In worst case, the loop runs floor(n/2) times. The worst case happens when n is of the form 2x – 1.

An efficient solution is to use bitwise left shift operator to find all powers of 2 starting from 1. For every power check if it is smaller than or equal to n or not. Below is the implementation of the idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find highest power of 2 smaller
// than or equal to n.
#include<bits/stdc++.h>
using namespace std;
  
int highestPowerof2(unsigned int n)
{
    // Invalid input
    if (n < 1)
        return 0;
  
    int res = 1;
  
    // Try all powers starting from 2^1
    for (int i=0; i<8*sizeof(unsigned int); i++)
    {
        int curr = 1 << i;
  
        // If current power is more than n, break
        if (curr > n)
           break;
  
        res = curr;
    }
  
    return res;
}
  
// Driver code
int main()
{
    int n = 10;
    cout << highestPowerof2(n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find 
// highest power of 2 smaller
// than or equal to n.
import java.io.*;
  
class GFG 
{
static int highestPowerof2(int n)
{
    // Invalid input
    if (n < 1)
        return 0;
  
    int res = 1;
  
    // Try all powers 
    // starting from 2^1
    for (int i = 0; i < 8 * Integer.BYTES; i++)
    {
        int curr = 1 << i;
  
        // If current power is 
        // more than n, break
        if (curr > n)
        break;
  
        res = curr;
    }
  
    return res;
}
  
// Driver code
public static void main(String[] args) 
{
    int n = 10;
    System.out.println(highestPowerof2(n));
}
}
  
// This code is contributed aj_36

chevron_right


python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find highest power of 2 smaller
# than or equal to n.
  
import sys
  
def highestPowerof2( n):
  
    # Invalid input
    if (n < 1):
        return 0
   
    res = 1
   
    #Try all powers starting from 2^1
    for i in range(8*sys.getsizeof(n)):
      
        curr = 1 << i
   
        # If current power is more than n, break
        if (curr > n):
             break
   
        res = curr
   
    return res
   
# Driver code
if __name__ == "__main__":
  
    n = 10
    print(highestPowerof2(n))
    

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find 
// highest power of 2 smaller
// than or equal to n.
using System;
  
class GFG
{
static int highestPowerof2(int n)
{
    // Invalid input
    if (n < 1)
        return 0;
  
    int res = 1;
  
    // Try all powers 
    // starting from 2^1
    for (int i = 0; i < 8 * sizeof(uint); i++)
    {
        int curr = 1 << i;
  
        // If current power is 
        // more than n, break
        if (curr > n)
        break;
  
        res = curr;
    }
  
    return res;
}
  
// Driver code
static public void Main ()
{
    int n = 10;
    Console.WriteLine(highestPowerof2(n));
}
}
  
// This code is contributed ajit

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find highest
// power of 2 smaller
// than or equal to n.
  
function highestPowerof2($n)
{
    // Invalid input
    if ($n < 1)
        return 0;
  
    $res = 1;
  
    // Try all powers starting 
    // from 2^1
    for ($i = 0; $i < 8 * PHP_INT_SIZE; $i++)
    {
        $curr = 1 << $i;
  
        // If current power is
        // more than n, break
        if ($curr > $n)
        break;
  
        $res = $curr;
    }
  
    return $res;
}
  
// Driver code
$n = 10;
echo highestPowerof2($n);
      
// This code is contributed
// by m_kit
?>

chevron_right



Output :

8

A Solution using Log
Thanks to Anshuman Jha for suggesting this solution.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find highest power of 2 smaller
// than or equal to n.
#include<bits/stdc++.h>
using namespace std;
  
int highestPowerof2(int n)
{
   int p = (int)log2(n);
   return (int)pow(2, p); 
}
  
// Driver code
int main()
{
    int n = 10;
    cout << highestPowerof2(n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find 
// highest power of 2 
// smaller than or equal to n.
import java.io.*;
  
class GFG 
{
static int highestPowerof2(int n)
{
      
    int p = (int)(Math.log(n) / 
                  Math.log(2));
    return (int)Math.pow(2, p); 
}
  
// Driver code
public static void main (String[] args) 
{
    int n = 10;
    System.out.println(highestPowerof2(n));
}
}
  
// This code is contributed
// by m_kit

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find highest 
# power of 2 smaller than or 
# equal to n.
import math
  
def highestPowerof2(n):
  
    p = int(math.log(n, 2));
    return int(pow(2, p)); 
  
# Driver code
n = 10;
print(highestPowerof2(n));
  
# This code is contributed by mits

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find 
// highest power of 2 
// smaller than or equal to n.
using System;
  
class GFG
{
static int highestPowerof2(int n)
{
    int p = (int)(Math.Log(n) / 
                   Math.Log(2));
    return (int)Math.Pow(2, p); 
}
  
// Driver code
static public void Main ()
{
    int n = 10;
    Console.WriteLine(highestPowerof2(n));
}
}
  
// This code is contributed
// by ajit

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find highest 
// power of 2 smaller than or 
// equal to n.
function highestPowerof2($n)
{
    $p = (int)log($n, 2);
    return (int)pow(2, $p); 
}
  
// Driver code
$n = 10;
echo highestPowerof2($n);
  
// This code is contributed by ajit
?>

chevron_right



Output :

8

Application Problem:
Some people are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue.
Print the position(original queue) of that person who is left.
Examples :

Input: n = 10
Output:8
Explanation : 
1 2 3 4 5 6 7 8 9 10  ===>Given queue
    2 4 6 8 10
       4 8
        8

Input: n = 17
Input: 16
Explanation : 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  ===>Given queue
        2 4 6 8 10 12 14 16
            4 8 12 16
              8 16
               16

Related Article :
Power of 2 greater than or equal to a given number.

This article is contributed by Sahil Chhabra. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up