Highest power of 2 less than or equal to given Integer
Last Updated :
28 Feb, 2023
Given an integer N, the task is to find the highest power of 2 that is smaller than or equal to N.
Examples:
Input: N = 9
Output: 8
Explanation:
Highest power of 2 less than 9 is 8.
Input: N = -20
Output: -32
Explanation:
Highest power of 2 less than -20 is -32.
Input: N = -84
Output: -128
Approach: The idea is to use logarithm to solve the above problem. For any given number N, it can be either positive or negative. The following task can be performed for each case:
- If the input is positive: floor(log2(N)) can be calculated.
- If the input is negative: ceil(log2(N)) can be calculated and a -ve sign can be added to the value.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the lowest power of 2 close to given
// positive number
int powOfPositive(int n)
{
// Floor function is used to determine the value close
// to the number
int pos = floor(log2(n));
return pow(2, pos);
}
// Function to return the lowest power of 2 close to given
// negative number
int powOfNegative(int n)
{
// Ceil function is used for negative numbers as -1 >
// -4. It would be opposite to positive numbers where 1 < 4
int pos = ceil(log2(n));
return (-1 * pow(2, pos));
}
// Function to find the highest power of 2
void highestPowerOf2(int n)
{
// To check if the given number is positive or negative
if (n > 0)
cout << powOfPositive(n);
else {
// If the number is negative, then the ceil of the
// positive number is calculated and negative sign
// is added
n = -n;
cout << powOfNegative(n);
}
}
// Driver code
int main()
{
int n = -24;
highestPowerOf2(n);
return 0;
}
// This code is contributed by Sania Kumari Gupta
C
// C implementation of the above approach
#include <math.h>
#include <stdio.h>
// Function to return the lowest power of 2 close to given
// positive number
int powOfPositive(int n)
{
// Floor function is used to determine the value close
// to the number
int pos = floor(log2(n));
return pow(2, pos);
}
// Function to return the lowest power of 2 close to given
// negative number
int powOfNegative(int n)
{
// Ceil function is used for negative numbers as -1 >
// -4. It would be opposite to positive numbers where 1 < 4
int pos = ceil(log2(n));
return (-1 * pow(2, pos));
}
// Function to find the highest power of 2
void highestPowerOf2(int n)
{
// To check if the given number is positive or negative
if (n > 0)
printf("%d", powOfPositive(n));
else {
// If the number is negative, then the ceil of the
// positive number is calculated and negative sign
// is added
n = -n;
printf("%d", powOfNegative(n));
}
}
// Driver code
int main()
{
int n = -24;
highestPowerOf2(n);
return 0;
}
// This code is contributed by Sania Kumari Gupta
Java
// Java implementation of the above approach
class GFG
{
// Function to return the lowest power
// of 2 close to given positive number
static int powOfPositive(int n)
{
// Floor function is used to determine
// the value close to the number
int pos = (int)Math.floor((Math.log(n)/Math.log(2)));
return (int)Math.pow(2, pos);
}
// Function to return the lowest power
// of 2 close to given negative number
static int powOfNegative(int n)
{
// Ceil function is used for negative numbers
// as -1 > -4. It would be opposite
// to positive numbers where 1 < 4
int pos = (int)Math.ceil((Math.log(n)/Math.log(2)));
return (int)(-1 * Math.pow(2, pos));
}
// Function to find the highest power of 2
static void highestPowerOf2(int n)
{
// To check if the given number
// is positive or negative
if (n > 0)
{
System.out.println(powOfPositive(n));
}
else
{
// If the number is negative,
// then the ceil of the positive number
// is calculated and
// negative sign is added
n = -n;
System.out.println(powOfNegative(n));
}
}
// Driver code
public static void main (String[] args)
{
int n = -24;
highestPowerOf2(n);
}
}
// This code is contributed by AnkitRai01
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to return the lowest power
// of 2 close to given positive number
static int powOfPositive(int n)
{
// Floor function is used to determine
// the value close to the number
int pos = (int)Math.Floor((Math.Log(n)/Math.Log(2)));
return (int)Math.Pow(2, pos);
}
// Function to return the lowest power
// of 2 close to given negative number
static int powOfNegative(int n)
{
// Ceil function is used for negative numbers
// as -1 > -4. It would be opposite
// to positive numbers where 1 < 4
int pos = (int)Math.Ceiling((Math.Log(n)/Math.Log(2)));
return (int)(-1 * Math.Pow(2, pos));
}
// Function to find the highest power of 2
static void highestPowerOf2(int n)
{
// To check if the given number
// is positive or negative
if (n > 0)
{
Console.WriteLine(powOfPositive(n));
}
else
{
// If the number is negative,
// then the ceil of the positive number
// is calculated and
// negative sign is added
n = -n;
Console.WriteLine(powOfNegative(n));
}
}
// Driver code
public static void Main()
{
int n = -24;
highestPowerOf2(n);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the above approach
from math import floor,ceil,log2
# Function to return the lowest power
# of 2 close to given positive number
def powOfPositive(n) :
# Floor function is used to determine
# the value close to the number
pos = floor(log2(n));
return 2**pos;
# Function to return the lowest power
# of 2 close to given negative number
def powOfNegative(n) :
# Ceil function is used for negative numbers
# as -1 > -4. It would be opposite
# to positive numbers where 1 < 4
pos = ceil(log2(n));
return (-1 * pow(2, pos));
# Function to find the highest power of 2
def highestPowerOf2(n) :
# To check if the given number
# is positive or negative
if (n > 0) :
print(powOfPositive(n));
else :
# If the number is negative,
# then the ceil of the positive number
# is calculated and
# negative sign is added
n = -n;
print(powOfNegative(n));
# Driver code
if __name__ == "__main__" :
n = -24;
highestPowerOf2(n);
# This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript implementation of the above approach
// Function to return the lowest power
// of 2 close to given positive number
function powOfPositive(n)
{
// Floor function is used to determine
// the value close to the number
let pos = Math.floor(Math.log2(n));
return Math.pow(2, pos);
}
// Function to return the lowest power
// of 2 close to given negative number
function powOfNegative(n)
{
// Ceil function is used for negative numbers
// as -1 > -4. It would be opposite
// to positive numbers where 1 < 4
let pos = Math.ceil(Math.log2(n));
return (-1 * Math.pow(2, pos));
}
// Function to find the highest power of 2
function highestPowerOf2(n)
{
// To check if the given number
// is positive or negative
if (n > 0)
{
document.write(powOfPositive(n));
}
else
{
// If the number is negative,
// then the ceil of the positive number
// is calculated and
// negative sign is added
n = -n;
document.write(powOfNegative(n));
}
}
// Driver code
let n = -24;
highestPowerOf2(n);
// This code is contributed by mohit kumar 29
</script>
Time Complexity: O(log2(log2n))
Auxiliary Space: O(1)
Another Approach: we can use Bits manipulation in this way :
1.If number is positive- Then our answer will be pow(2,i) where i is leftmost set bit . Because if number is equal to pow(2,i), Then number is already power of 2, and if number > pow(2,i) , any power of 2 can not be greater than pow(2,i) as in bit concepts.
2.If number is negative- Let i is leftmost set bit .Then our answer will be pow(2,i) if(pow(2,i)==num). else our answer will be pow(2,i+1) because we are taking in negative.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function find highestpowerof2 <= n
void highestPowerOf2(int n)
{ // leftmost- keep track of leftmost set bit
int set_bits = 0, leftmost, highest;
// iterate all sits of integer
for (int i = 0; i <= 32; i++) {
int val = pow(2, i);
int Bitwise_AND = val & abs(n); // Bitwise AND
if (Bitwise_AND
> 0) // If Bitwise_AND > 0 means sit is set
{
leftmost = i; // update leftmost set bit
highest = pow(
2, leftmost); // Update
// highest(highestpowerof2)
set_bits++; // count set bits
}
if (val >= abs(n)) {
break;
} // if we have found leftmost set bit ,break
}
if (n < 0) // make +highest to -highest
{
if (set_bits
> 1) // means -n=-pow(2,i)-pow(2,j).....
{
highest = pow(2, leftmost + 1);
}
highest = -1 * highest;
}
cout << highest; // Print highestPowerOf2 <= n
}
// Driver code
int main()
{
int n = -24;
// Function call
highestPowerOf2(n);
return 0;
}
// This Approach is contributed by nikhilsainiofficial546
Java
import java.lang.Math;
class Main {
// Function to find highest power of 2 <= n
static void highestPowerOf2(int n) {
int set_bits = 0, leftmost = 0, highest = 0;
// iterate over all bits of integer
for (int i = 0; i <= 31; i++) {
int val = (int) Math.pow(2, i);
int Bitwise_AND = val & Math.abs(n); // Bitwise AND
if (Bitwise_AND > 0) { // If Bitwise_AND > 0 means bit is set
leftmost = i; // update leftmost set bit
highest = (int) Math.pow(2, leftmost); // Update highest(highest power of 2)
set_bits++; // count set bits
}
if (val >= Math.abs(n)) {
break;
} // if we have found leftmost set bit, break
}
if (n < 0) { // make +highest to -highest
if (set_bits > 1) { // means -n=-pow(2,i)-pow(2,j).....
highest = (int) Math.pow(2, leftmost + 1);
}
highest = -1 * highest;
}
System.out.println(highest); // Print highest power of 2 <= n
}
// Driver code
public static void main(String[] args) {
int n = -24;
highestPowerOf2(n); // Function call
}
}
Python3
import math
def highestPowerOf2(n):
set_bits = 0
leftmost = 0
highest = 0
for i in range(32): # iterate over all bits of integer
val = int(math.pow(2, i))
Bitwise_AND = val & abs(n) # Bitwise AND
if (Bitwise_AND > 0): # If Bitwise_AND > 0 means bit is set
leftmost = i # update leftmost set bit
highest = int(math.pow(2, leftmost)) # Update highest(highest power of 2)
set_bits += 1 # count set bits
if (val >= abs(n)):
break # if we have found leftmost set bit, break
if (n < 0): # make +highest to -highest
if (set_bits > 1): # means -n=-pow(2,i)-pow(2,j).....
highest = int(math.pow(2, leftmost + 1))
highest = -1 * highest
print(highest) # Print highest power of 2 <= n
# Driver code
n = -24
highestPowerOf2(n) # Function call
C#
// C# implementation of the above approach
using System;
class GFG {
// Function find highestpowerof2 <= n
static void highestPowerOf2(int n)
{
// leftmost- keep track of leftmost set bit
int set_bits = 0, leftmost = 0, highest = 0;
// iterate all sits of integer
for (int i = 0; i <= 32; i++) {
int val = (int)Math.Pow(2, i);
int bitwiseAnd
= val & Math.Abs(n); // Bitwise AND
// If Bitwise_AND > 0 means sit is set
if (bitwiseAnd > 0) {
leftmost = i; // update leftmost set bit
// Update highest(highestpowerof2)
highest = (int)Math.Pow(2, leftmost);
// count set bits
set_bits++;
}
// if we have found leftmost set bit ,break
if (val >= Math.Abs(n)) {
break;
}
}
// make +highest to -highest
if (n < 0) {
if (set_bits > 1) {
highest = (int)Math.Pow(
2,
leftmost
+ 1); // means
// -n=-pow(2,i)-pow(2,j).....
}
highest = -1 * highest;
}
Console.WriteLine(highest);
}
// Driver code
public static void Main()
{
int n = -24;
// Function call
highestPowerOf2(n);
}
}
JavaScript
// JavaScript implementation of the above approach
// Function to find highest power of 2 <= n
function highestPowerOf2(n)
{
let set_bits = 0, leftmost, highest;
// Iterate all bits of the integer
for (let i = 0; i <= 32; i++) {
let val = Math.pow(2, i);
let Bitwise_AND
= val & Math.abs(n); // Bitwise AND with
// absolute value of n
// If Bitwise_AND > 0 means bit is set
if (Bitwise_AND > 0) {
leftmost = i; // Update leftmost set bit
highest = Math.pow(
2, leftmost); // Update highest (highest
// power of 2)
set_bits++; // Count set bits
}
// If we have found leftmost set bit, break
if (val >= Math.abs(n)) {
break;
}
}
// If n is negative, make +highest to -highest
if (n < 0) {
if (set_bits > 1) {
// Means -n = -pow(2,i) - pow(2,j) .....
highest = Math.pow(2, leftmost + 1);
}
highest = -1 * highest;
}
console.log(highest); // Print highest power of 2 <= n
}
// Driver code
let n = -24;
highestPowerOf2(n); // Output: -32
Time Complexity: O(log2n) , Because we are breaking loop , if leftmost set bit is found
Auxiliary Space: O(1)
Similar Reads
Find all powers of 2 less than or equal to a given number
Given a positive number N, the task is to find out all the perfect powers of two which are less than or equal to the given number N. Examples: Input: N = 63 Output: 32 16 8 4 2 1 Explanation: There are total of 6 powers of 2, which are less than or equal to the given number N. Input: N = 193 Output:
6 min read
Largest number less than or equal to N/2 which is coprime to N
Given a number N, the task is to find the largest positive integer less than or equal to N/2 which is coprime to N. Note: Two number A and B are considered to coprime if gcd(A, B) = 1. It is also given that 2 < N < 10^18.Examples: Input: N = 50 Output: 23 GCD(50, 23) = 1 Input: N = 100 Output:
9 min read
Largest of two distinct numbers without using any conditional statements or operators
Given two positive and distinct numbers, the task is to find the greatest of two given numbers without using any conditional statements(if...) and operators(?: in C/C++/Java).Examples: Input: a = 14, b = 15 Output: 15 Input: a = 14, b = 14 Output: 14 Input: a = 1233133, b = 124 Output: 1233133The Ap
3 min read
C++ Program to Find the Second Largest Element in an Array
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
3 min read
Maximum OR value of a pair in an Array | Set 2
Given an array arr[] of N positive elements, the task is to find the maximum bitwise OR value of a pair from the given array.Examples: Input: arr[] = {3, 6, 8, 16} Output: 24 Explanation: The pair giving maximum OR value is (8, 16) 8|16 = 24Input: arr[] = {8, 7, 3, 12} Output: 15 Explanation: There
5 min read
Find a distinct pair (x, y) in given range such that x divides y
Given a range of positive integers from l to r. Find such a pair of integers (x, y) that l <= x, y <= r, x != y and x divide y. If there are multiple pairs, you need to find any one of them. Examples: Input : 1 10 Output : 1 2 Input : 2 4 Output : 2 4 The brute force solution is to traverse th
6 min read
Maximum value of short int in C++
In this article, we will discuss the short int data type in C++. This data type in C++ is used to store 16-bit integers. Some properties of the short int data type are: Being a signed data type, it can store positive values as well as negative values.Takes a size of 16 bits, where 1 bit is used to s
3 min read
Maximum value of long long int in C++
In this article, we will discuss the long long int data type in C++. long long int data type in C++ is used to store 64-bit integers. It is one of the largest data types to store integer values, unlike unsigned long long int both positive and negative. Some properties of the long long int data type
2 min read
Select maximum types from an array with limit of n/2
Given an array arr[] of n items, with n being an even number and arr[i] representing the type of item. The task is to find the maximum number of different types of items a person can select with a limit on total selected items as n/2.Examples:Input: arr[] = {2, 2, 3, 1}Output: 2Explanation: Person c
4 min read
Maximum value of unsigned int in C++
In this article, we will discuss the maximum value of unsigned int in C++. Unsigned int data type in C++ is used to store 32-bit integers.The keyword unsigned is a data type specifier, which only represents non-negative integers i.e. positive numbers and zero. Some properties of the unsigned int dat
2 min read