Given a number n, find the highest power of 2 that divides n.
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:
- Highest power of 2 that divides a number represented in binary
- Highest power of 2 less than or equal to given number
- Check if given number is a power of d where d is a power of 2
- Largest number that divides x and is co-prime with y
- Check if the sum of digits of a number N divides it
- Minimum value that divides one number and divisible by other
- Check if a M-th fibonacci number divides N-th fibonacci number
- Find whether a given number is a power of 4 or not
- Check if a number is power of 8 or not
- Number of pairs whose sum is a power of 2
- Find number of subarrays with XOR value a power of 2
- Compute modulus division by a power-of-2-number
- Find the sum of power of bit count raised to the power B
- Minimum removals in a number to be divisible by 10 power raised to K
- Breaking a number such that first part is integral division of second by a power of 10
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.