Highest power of 2 less than or equal to given number
Last Updated :
25 Oct, 2022
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++
// 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;
}
// This code is contributed by Sania Kumari Gupta
// (kriSania804)
C
// C program to find highest power of 2 smaller
// than or equal to n.
#include <stdio.h>
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;
printf("%d", highestPowerof2(n));
return 0;
}
// This code is contributed by Sania Kumari Gupta
// (kriSania804)
Java
// Java program 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.print(highestPowerof2(n));
}
}
// This code is contributed by 29AjayKumar
Python3
# 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
C#
// 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
PHP
<?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
?>
JavaScript
<script>
// JavaScript program to find highest power
// of 2 smaller than or equal to n.
function highestPowerof2(n)
{
let res = 0;
for (let i = n; i >= 1; i--)
{
// If i is a power of 2
if ((i & (i - 1)) == 0)
{
res = i;
break;
}
}
return res;
}
// Driver code
let n = 10;
document.write(highestPowerof2(n));
</script>
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.
Auxiliary Space : O(1) since only constant space is used for variables
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++
// 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;
}
// This code is contributed by Sania Kumari Gupta
C
// C program to find highest power of 2 smaller
// than or equal to n.
#include <stdio.h>
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;
printf("%d", highestPowerof2(n));
return 0;
}
// This code is contributed by Sania Kumari Gupta
Java
// 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
python3
# 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))
C#
// 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
PHP
<?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
?>
JavaScript
<script>
function highestPowerof2(n)
{
// Invalid input
if (n < 1)
return 0;
let res = 1;
// Try all powers starting from 2^1
for (let i=0; i<8; i++)
{
let curr = 1 << i;
// If current power is more than n, break
if (curr > n)
break;
res = curr;
}
return res;
}
// Driver code
let n = 10;
document.write(highestPowerof2(n));
</script>
Time Complexity: O(32)
Auxiliary Space: O(1)
A Solution using Log(n)
Thanks to Anshuman Jha for suggesting this solution.
C++
// 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;
}
Java
// 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
Python3
# 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
C#
// 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
PHP
<?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
?>
JavaScript
<script>
// Javascript program to find
// highest power of 2
// smaller than or equal to n.
function highestPowerof2(n)
{
let p = parseInt(Math.log(n) / Math.log(2), 10);
return Math.pow(2, p);
}
let n = 10;
document.write(highestPowerof2(n));
// This code is contributed by divyeshrabadiya07.
</script>
Time Complexity: O(logn)
Auxiliary Space: O(1)
Solution using bitmasks :
C++
// C++ program to find highest power of 2 smaller
// than or equal to n.
#include <iostream>
using namespace std;
unsigned highestPowerof2(unsigned x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
// Then we remove all but the top bit by xor'ing the
// string of 1's with that string of 1's shifted one to
// the left, and we end up with just the one top bit
// followed by 0's.
return x ^ (x >> 1);
}
int main()
{
int n = 10;
cout << highestPowerof2(n) << "\n";
return 0;
}
// This code is contributed by Rudrakshi.
Java
// Java program to find highest power of 2 smaller
// than or equal to n.
import java.io.*;
class GFG
{
static int highestPowerof2(int x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
// Then we remove all but the top bit by xor'ing the
// string of 1's with that string of 1's shifted one to
// the left, and we end up with just the one top bit
// followed by 0's.
return x ^ (x >> 1);
}
// Driver code
public static void main (String[] args)
{
int n = 10;
System.out.println(highestPowerof2(n));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 program to find highest power of 2 smaller than or equal to n.
def highestPowerof2(x):
# check for the set bits
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
# Then we remove all but the top bit by xor'ing the
# string of 1's with that string of 1's shifted one to
# the left, and we end up with just the one top bit
# followed by 0's.
return x ^ (x >> 1)
n = 10
print(highestPowerof2(n))
# This code is contributed by divyesh072019.
C#
// C# program to find highest power of 2 smaller
// than or equal to n.
using System;
public class GFG
{
static int highestPowerof2(int x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
// Then we remove all but the top bit by xor'ing the
// string of 1's with that string of 1's shifted one to
// the left, and we end up with just the one top bit
// followed by 0's.
return x ^ (x >> 1);
}
// Driver code
public static void Main(String[] args)
{
int n = 10;
Console.WriteLine(highestPowerof2(n));
}
}
// This code is contributed by umadevi9616
JavaScript
<script>
// Javascript program to find highest power of 2 smaller
// than or equal to n.
function highestPowerof2(x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
// Then we remove all but the top bit by xor'ing the
// string of 1's with that string of 1's shifted one to
// the left, and we end up with just the one top bit
// followed by 0's.
return x ^ (x >> 1);
}
let n = 10;
document.write(highestPowerof2(n))
// This code is contributed by rag2127
</script>
Time Complexity: O(1)
Auxiliary Space: O(1) since only constant space is used for variables
A solution using MSB
If the given number is the power of two then it is the required number otherwise set only the most significant bit which gives us the required number.
C++
// C++ program to find
// smallest power of 2
// smaller than or equal to n
#include <iostream>
using namespace std;
long long highestPowerof2(long long N)
{
// if N is a power of two simply return it
if (!(N & (N - 1)))
return N;
// else set only the most significant bit
return 0x8000000000000000 >> (__builtin_clzll(N));
}
// Driver Code
int main()
{
long long n = 5;
cout << highestPowerof2(n);
return 0;
}
// This code is contributed by phasing17
Java
// Java program to find
// smallest power of 2
// smaller than or equal to n
import java.util.*;
class GFG
{
static int highestPowerof2(int N)
{
// if N is a power of two simply return it
if ((N & (N - 1)) == 0)
return N;
// else set only the most significant bit
return (1 << (Integer.toBinaryString(N).length() - 1));
}
// Driver Code
public static void main(String[] args)
{
int n = 5;
System.out.println(highestPowerof2(n));
}
}
// This code is contributed by phasing17
Python3
# Python3 program to find
# smallest power of 2
# smaller than or equal to n
def highestPowerof2(N):
# if N is a power of two simply return it
if (not (N & (N - 1))):
return N;
# else set only the most significant bit
return 0x8000000000000000 >> (64 - N.bit_length())
# Driver Code
n = 5;
print(highestPowerof2(n))
# This code is contributed by phasing17
C#
// C# program to find
// smallest power of 2
// smaller than or equal to n
using System;
using System.Collections.Generic;
class GFG
{
static int highestPowerof2(int N)
{
// if N is a power of two simply return it
if ((N & (N - 1)) == 0)
return N;
// else set only the most significant bit
return (1 << ((Convert.ToString(N, 2).Length) - 1));
}
// Driver Code
public static void Main(string[] args)
{
int n = 5;
Console.WriteLine(highestPowerof2(n));
}
}
// This code is contributed by phasing17
JavaScript
// JS program to find
// smallest power of 2
// smaller than or equal to n
function highestPowerof2(N)
{
// if N is a power of two simply return it
if (!(N & (N - 1)))
return N;
// else set only the most significant bit
return 1 << ((N.toString(2)).length) - 1;
}
// Driver Code
let n = 5;
console.log(highestPowerof2(n));
// This code is contributed by phasing17
Time Complexity : O(1) as counting leading zeroes can cause at most O(64) time complexity.
Auxiliary Space: O(1)
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.
Similar Reads
Highest power of two that divides a given number Given a number n, find the highest power of 2 that divides n.Examples: Input : n = 48 Output : 16 Highest power of 2 that divides 48 is 16.Input : n = 5 Output : 1 Highest power of 2 that divides 5 is 1. A simple solution is to try all powers of 2 one by one starting from 1, then 2, then 4 and so on
5 min read
Highest power of a number that divides other number | Set - 2 Given two numbers N and M(M > 1), the task is to find the highest power of M that divides N. Examples: Input: N = 12, M = 2Output: 2Explanation: The powers of 2 which divide 12 are 1 and 2 (21 = 2 and 22 = 4 which both divide 12). The higher power is 2, hence consider 2. Input: N = 500, M = 5Outp
5 min read
Kth largest odd number in a given range Given two variables L and R, indicating a range of integers from L to R inclusive, and a number K, the task is to find Kth largest odd number. If K > number of odd numbers in the range L to R then return 0. Examples: Input: L = -10, R = 10, K = 8Output: -5Explanation: The odd Numbers in the range
7 min read
Largest set of numbers upto N such that either i or i/2 is present Given a positive integer N, the task is to find the length of largest set that can be generated such that if i is present, then i/2 will not be present and 1<=i<=N. Note: For multiple solutions, print anyone satisfying the condition. Examples: Input: N = 2Output: 1Explanation: There are two po
5 min read
Largest proper fraction with sum of numerator and denominator equal to a given number We are provided with a number N. Find the biggest proper fraction a/b such that a + b = N. Following are constraints for fraction. a/b is a proper fraction if a<b and a and b are coprimes i.e no common factor of a and b.There can be multiple proper fractions with sum of numerator and denominator
7 min read
Arrange the numbers in the Array as per given inequalities Given a list of N distinct integers and a list of N-1 inequality signs, the task is to insert the integers between the inequality signs, such that the final inequality formed always holds true.Note: The order of the inequality signs should not be changed. Examples: Input: Integers: [ 2, 5, 1, 0 ], S
6 min read