Write a function that, for a given no n, finds a number p which is greater than or equal to n and is the smallest power of 2.
Examples :
Input: n = 5
Output: 8
Input: n = 17
Output: 32
Input : n = 32
Output: 32
Method 1: Using log2(number)
- Calculate the log2(N) and store it into a variable say ‘a’
- Check if pow(2, a) is equals to N
- Otherwise, return pow(2, a + 1)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long nearestPowerOf2( long long N)
{
long long a = log2(N);
if ( pow (2, a) == N)
return N;
return pow (2, a + 1);
}
int main()
{
unsigned int n = 5;
cout << nearestPowerOf2(n);
return 0;
}
|
Java
import java.io.*;
public class GFG {
public static long nearestPowerOf2( long N)
{
long a = ( int )(Math.log(N) / Math.log( 2 ));
if (Math.pow( 2 , a) == N)
return N;
return ( long ) Math.pow( 2 , a + 1 );
}
public static void main (String[] args) {
long n = 5 ;
System.out.println(nearestPowerOf2(n));
}
}
|
Python3
import math
def nearestPowerOf2(N):
a = int (math.log2(N))
if 2 * * a = = N:
return N
return 2 * * (a + 1 )
if __name__ = = "__main__" :
n = 5
print (nearestPowerOf2(n))
|
C#
using System;
public class GFG {
public static long nearestPowerOf2( long N)
{
long a = ( int )(Math.Log(N) / Math.Log(2));
if (Math.Pow(2, a) == N)
return N;
return ( long ) Math.Pow(2, a + 1);
}
public static void Main (String[] args) {
long n = 5;
Console.WriteLine(nearestPowerOf2(n));
}
}
|
Javascript
function nearestPowerOf2(N)
{
var a = Math.floor(Math.log2(N));
if (Math.pow(2, a) === N) {
return N;
}
return Math.pow(2, a + 1);
}
var n = 5;
console.log(nearestPowerOf2(n));
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Example :
Let us try for 17
pos = 5
p = 32
Method 2 (By getting the position of only set bit in result )
/* If n is a power of 2 then return n */
1 If (n & !(n&(n-1))) then return n
2 Else keep right shifting n until it becomes zero
and count no of shifts
a. Initialize: count = 0
b. While n ! = 0
n = n>>1
count = count + 1
/* Now count has the position of set bit in result */
3 Return (1 << count)
Example :
Let us try for 17
count = 5
p = 32
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int nextPowerOf2(unsigned int n)
{
unsigned count = 0;
if (n && !(n & (n - 1)))
return n;
while ( n != 0)
{
n >>= 1;
count += 1;
}
return 1 << count;
}
int main()
{
unsigned int n = 0;
cout << nextPowerOf2(n);
return 0;
}
|
C
#include<stdio.h>
unsigned int nextPowerOf2(unsigned int n)
{
unsigned count = 0;
if (n && !(n & (n - 1)))
return n;
while ( n != 0)
{
n >>= 1;
count += 1;
}
return 1 << count;
}
int main()
{
unsigned int n = 0;
printf ( "%d" , nextPowerOf2(n));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int nextPowerOf2( int n)
{
int count = 0 ;
if (n > 0 && (n & (n - 1 )) == 0 )
return n;
while (n != 0 )
{
n >>= 1 ;
count += 1 ;
}
return 1 << count;
}
public static void main(String args[])
{
int n = 0 ;
System.out.println(nextPowerOf2(n));
}
}
|
Python3
def nextPowerOf2(n):
count = 0
if (n and not (n & (n - 1 ))):
return n
while ( n ! = 0 ):
n >> = 1
count + = 1
return 1 << count
n = 0
print (nextPowerOf2(n))
|
C#
using System;
class GFG
{
static int nextPowerOf2( int n)
{
int count = 0;
if (n > 0 && (n & (n - 1)) == 0)
return n;
while (n != 0)
{
n >>= 1;
count += 1;
}
return 1 << count;
}
public static void Main()
{
int n = 0;
Console.WriteLine(nextPowerOf2(n));
}
}
|
PHP
<?php
function nextPowerOf2( $n )
{
$count = 0;
if ( $n && !( $n &( $n - 1)))
return $n ;
while ( $n != 0)
{
$n >>= 1;
$count += 1;
}
return 1 << $count ;
}
$n = 0;
echo (nextPowerOf2( $n ));
?>
|
Javascript
<script>
function nextPowerOf2(n)
{
var count = 0;
if (n && !(n & (n - 1)))
return n;
while ( n != 0)
{
n >>= 1;
count += 1;
}
return 1 << count;
}
var n = 0;
document.write(nextPowerOf2(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Method 3(Shift result one by one)
Thanks to coderyogi for suggesting this method . This method is a variation of method 2 where instead of getting count, we shift the result one by one in a loop.
C++
#include<bits/stdc++.h>
using namespace std;
unsigned int nextPowerOf2(unsigned int n)
{
unsigned int p = 1;
if (n && !(n & (n - 1)))
return n;
while (p < n)
p <<= 1;
return p;
}
int main()
{
unsigned int n = 5;
cout << nextPowerOf2(n);
return 0;
}
|
C
#include<stdio.h>
unsigned int nextPowerOf2(unsigned int n)
{
unsigned int p = 1;
if (n && !(n & (n - 1)))
return n;
while (p < n)
p <<= 1;
return p;
}
int main()
{
unsigned int n = 5;
printf ( "%d" , nextPowerOf2(n));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int nextPowerOf2( int n)
{
int p = 1 ;
if (n > 0 && (n & (n - 1 )) == 0 )
return n;
while (p < n)
p <<= 1 ;
return p;
}
public static void main(String args[])
{
int n = 5 ;
System.out.println(nextPowerOf2(n));
}
}
|
Python3
def nextPowerOf2(n):
p = 1
if (n and not (n & (n - 1 ))):
return n
while (p < n) :
p << = 1
return p;
n = 5
print (nextPowerOf2(n));
|
C#
using System;
class GFG
{
static int nextPowerOf2( int n)
{
int p = 1;
if (n > 0 && (n & (n - 1)) == 0)
return n;
while (p < n)
p <<= 1;
return p;
}
public static void Main()
{
int n = 5;
Console.Write(nextPowerOf2(n));
}
}
|
PHP
<?php
function nextPowerOf2( $n )
{
$p = 1;
if ( $n && !( $n & ( $n - 1)))
return $n ;
while ( $p < $n )
$p <<= 1;
return $p ;
}
$n = 5;
echo ( nextPowerOf2( $n ));
?>
|
Javascript
<script>
function nextPowerOf2( n)
{
p = 1;
if (n && !(n & (n - 1)))
return n;
while (p < n)
p <<= 1;
return p;
}
n = 5;
document.write (nextPowerOf2(n));
</script>
|
Time Complexity: O(log(n))
Auxiliary Space: O(1)
Method 4(Customized and Fast)
1. Subtract n by 1
n = n -1
2. Set all bits after the leftmost set bit.
/* Below solution works only if integer is 32 bits */
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
3. Return n + 1
Example :
Steps 1 & 3 of above algorithm are to handle cases
of power of 2 numbers e.g., 1, 2, 4, 8, 16,
Let us try for 17(10001)
step 1
n = n - 1 = 16 (10000)
step 2
n = n | n >> 1
n = 10000 | 01000
n = 11000
n = n | n >> 2
n = 11000 | 00110
n = 11110
n = n | n >> 4
n = 11110 | 00001
n = 11111
n = n | n >> 8
n = 11111 | 00000
n = 11111
n = n | n >> 16
n = 11110 | 00000
n = 11111
step 3: Return n+1
We get n + 1 as 100000 (32)
Program:
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int nextPowerOf2(unsigned int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
int main()
{
unsigned int n = 5;
cout << nextPowerOf2(n);
return 0;
}
|
C
#include <stdio.h>
unsigned int nextPowerOf2(unsigned int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
int main()
{
unsigned int n = 5;
printf ( "%d" , nextPowerOf2(n));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int nextPowerOf2( int n)
{
n--;
n |= n >> 1 ;
n |= n >> 2 ;
n |= n >> 4 ;
n |= n >> 8 ;
n |= n >> 16 ;
n++;
return n;
}
public static void main(String args[])
{
int n = 5 ;
System.out.println(nextPowerOf2(n));
}
}
|
Python3
def nextPowerOf2(n):
n - = 1
n | = n >> 1
n | = n >> 2
n | = n >> 4
n | = n >> 8
n | = n >> 16
n + = 1
return n
n = 5
print (nextPowerOf2(n))
|
C#
using System;
class GFG
{
static int nextPowerOf2( int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
public static void Main()
{
int n = 5;
Console.WriteLine(nextPowerOf2(n));
}
}
|
PHP
<?php
function nextPowerOf2( $n )
{
$n --;
$n |= $n >> 1;
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
$n ++;
return $n ;
}
$n = 5;
echo nextPowerOf2( $n );
?>
|
Javascript
<script>
function nextPowerOf2(n)
{
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n += 1
return n
}
n = 5;
document.write (nextPowerOf2(n));
</script>
|
Time Complexity : O(log(n))
Auxiliary Space: O(1)
Efficient approach:
If the given number is the power of two then it is the required number otherwise set only the left bit of most significant bit which gives us the required number.
C++
#include <iostream>
using namespace std;
long long nextPowerOf2( long long N)
{
if (!(N & (N - 1)))
return N;
return 0x8000000000000000 >> (__builtin_clzll(N) - 1);
}
int main()
{
long long n = 5;
cout << nextPowerOf2(n);
return 0;
}
|
C
#include <stdio.h>
long long nextPowerOf2( long long N)
{
if (!(N & (N - 1)))
return N;
return 0x8000000000000000 >> (__builtin_clzll(N) - 1);
}
int main()
{
long long n = 5;
printf ( "%lld" , nextPowerOf2(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static long nextPowerOf2( long N)
{
if ((N & (N - 1 )) == 0 )
return N;
return 0x4000000000000000L
>> (Long.numberOfLeadingZeros(N) - 2 );
}
public static void main(String args[])
{
long n = 5 ;
System.out.println(nextPowerOf2(n));
}
}
|
Python3
def nextPowerOf2(N):
if not (N & (N - 1 )):
return N
return int ( "1" + ( len ( bin (N)) - 2 ) * "0" , 2 )
n = 5
print (nextPowerOf2(n))
|
C#
using System;
using System.Linq;
class GFG {
static int nextPowerOf2( int N)
{
if ((N & (N - 1)) == 0)
return N;
return Convert.ToInt32(
"1"
+ new string ( '0' ,
Convert.ToString(N, 2).Length),
2);
}
public static void Main( string [] args)
{
int n = 5;
Console.WriteLine(nextPowerOf2(n));
}
}
|
Javascript
function nextPowerOf2(N)
{
if (!(N & (N - 1)))
return N;
return parseInt( "1" + "0" .repeat(N.toString(2).length), 2);
}
let n = 5;
console.log(nextPowerOf2(n));
|
Time Complexity : O(1) as counting leading zeroes can cause at most O(64) time complexity.
Auxiliary Space: O(1)
Related Post :
Highest power of 2 less than or equal to given number
References :
http://en.wikipedia.org/wiki/Power_of_2