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.
An efficient solution is based on bit magic. If we take a closer look, we can notice that, we basically need to find the number that has rightmost bit set at same position as n and all other bits as 0. For example, for n = 5 (101), our output is 001. For n = 48 (110000), our output is 010000
How do we find a number that has same rightmost set bit and all other bits as 0?
We follow below steps.
Let n = 48 (00110000)
Subtract one from n, i.e., we do n-1. We get 47(00101111)
Do negation of (n-1), i.e., we do ~(n-1). We get (11010000).
Do n & (~(n-1)), we get 00010000 which has value 16.
Below is the implementation of above approach:
C++
#include<iostream>
using namespace std;
int highestPowerOf2(int n)
{
return (n & (~(n - 1)));
}
int main()
{
int n = 48;
cout << highestPowerOf2(n);
return 0;
}
|
Java
class GFG
{
static int highestPowerOf2(int n)
{
return (n & (~(n - 1)));
}
public static void main(String []args)
{
int n = 48;
System.out.println(highestPowerOf2(n));
}
}
|
Python3
def highestPowerOf2(n):
return (n & (~(n - 1)))
if __name__=='__main__':
n = 48
print(highestPowerOf2(n))
|
C#
using System;
class GFG
{
static int highestPowerOf2(int n)
{
return (n & (~(n - 1)));
}
public static void Main()
{
int n = 48;
Console.Write(highestPowerOf2(n));
}
}
|
Javascript
<script>
function highestPowerOf2(n)
{
return (n & (~(n - 1)));
}
var n = 48;
document.write(highestPowerOf2(n));
</script>
|
PHP
<?php
function highestPowerOf2($n)
{
return ($n & (~($n - 1)));
}
$n = 48;
echo highestPowerOf2($n);
?>
|
Time Complexity: O(log2n)
Space Complexity:- O(1).
Approach – 2: This is also an efficient approach, where you can find the largest divisor of power two for a number ‘n’ using a predefined function in C for handling bits. Which is _builtin_ctz(n), this function helps you to find the trailing zeros of the number, and then you can see the bits-magic.
Input : n = 48 ~= (110000)2 // num of trailing zeros are = 4, so number of trailing zeros = 4
Output : 1<<4 =16 // pow(2,4) = 16 Highest power of 2 that divides 48 is 16.
Input : n = 21 ~= (10101)2 // no trailing zeros are present, so number of trailing zeros = 0
Output : 1<<0 =2 // pow(2,0)=1
Note: To know in the detail about such bits masking functions you can go through this article.
C++
#include <iostream>
using namespace std;
int main()
{
int n = 21;
int m = 48;
cout << "for " << n << " is " << (1 << __builtin_ctz(n))
<< endl;
cout << "for " << m << " is " << (1 << __builtin_ctz(m))
<< endl;
return 0;
}
|
C
#include <stdio.h>
int main()
{
int n = 21;
int m = 48;
printf("for %d is %d ", n, (1 << __builtin_ctz(n)));
printf("\nfor %d is %d ", m, (1 << __builtin_ctz(m)));
return 0;
}
|
Java
public class Main {
public static void main(String[] args)
{
int n = 21;
int m = 48;
System.out.println(
"for " + n + " is "
+ (1 << Integer.numberOfTrailingZeros(n)));
System.out.println(
"for " + m + " is "
+ (1 << Integer.numberOfTrailingZeros(m)));
}
}
|
Python3
n = 21
m = 48
print(f"for {n} is {1 << (n & -n).bit_length() - 1}")
print(f"for {m} is {1 << (m & -m).bit_length() - 1}")
|
C#
using System;
class Program {
static int FindLeastSignificantBitPosition(int num)
{
int position = 0;
while ((num & 1) == 0) {
num >>= 1;
position++;
}
return position;
}
static void Main()
{
int n = 21;
int m = 48;
int positionN = FindLeastSignificantBitPosition(n);
int positionM = FindLeastSignificantBitPosition(m);
Console.WriteLine("for " + n + " is "
+ (1 << positionN));
Console.WriteLine("for " + m + " is "
+ (1 << positionM));
}
}
|
Javascript
let n = 21;
let m = 48;
console.log(`for ${n} is ${1 << (n & -n).toString(2).length - 1}`);
console.log(`for ${m} is ${1 << (m & -m).toString(2).length - 1}`);
|
Output
for 21 is 1
for 48 is 16
Time Complexity: O(log2n)
Space Complexity: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!