The Wayback Machine - https://web.archive.org/web/20240723022830/https://www.geeksforgeeks.org/highest-power-of-two-that-divides-a-given-number/
Open In App

Highest power of two that divides a given number

Last Updated : 19 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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++




// CPP program to find highest power
// of 2 that divides n.
#include<iostream>
using namespace std;
 
int highestPowerOf2(int n)
{
    return (n & (~(n - 1)));
}
 
int main()
{
    int n = 48;
    cout << highestPowerOf2(n);
    return 0;
}


Java




// Java program to find highest power
// of 2 that divides n.
  
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




# Python3 program to find highest power
# of 2 that divides n.
 
def highestPowerOf2(n):
 
    return (n & (~(n - 1)))
 
 
#Driver code
if __name__=='__main__':
    n = 48
    print(highestPowerOf2(n))
 
# this code is contributed
# by ash264


C#




// C# program to find highest power
// of 2 that divides n.
using System;
 
class GFG
{
     
static int highestPowerOf2(int n)
{
    return (n & (~(n - 1)));
}
 
public static void Main()
{
    int n = 48;
    Console.Write(highestPowerOf2(n));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Javascript




<script>
 
// javascript program to find highest power
// of 2 that divides n.
  
 
      
function highestPowerOf2(n)
{
    return (n & (~(n - 1)));
}
 
var n = 48;
document.write(highestPowerOf2(n));
 
 
// This code is contributed by 29AjayKumar
 
</script>


PHP




<?php
// PHP program to find highest power
// of 2 that divides n.
 
function highestPowerOf2($n)
{
    return ($n & (~($n - 1)));
}
 
// Driver Code
$n = 48;
echo highestPowerOf2($n);
 
// This code is contributed
// by Sach_Code..
?>


Output

16


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;
}
 
// This code is contributed by Prajwal Kandekar


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 {
    // Function to find the position of the least
    // significant set bit
    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




// JavaScript code for above approach
 
// Taken n
let n = 21;
 
// Taken m
let m = 48;
 
// Printing answer
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)



Similar Reads

Highest power of a number that divides other number | Set - 2
Given two numbers N and M(M &gt; 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 = 5Output: 3. Naive and Bit Manipulation Approach: The na
5 min read
Highest power of a number that divides other number
Given two numbers N and M, the task is to find the highest power of M that divides N. Note: M &gt; 1 Examples: Input: N = 48, M = 4 Output: 2 48 % (4^2) = 0 Input: N = 32, M = 20 Output: 0 32 % (20^0) = 0 Brute Force Approach: The idea to solve this problem is to iterate from 1 to m and for each number, check if it is a factor of both n and m. If i
15+ min read
Highest power of 2 that divides a number represented in binary
Given binary string str, the task is to find the largest power of 2 that divides the decimal equivalent of the given binary number. Examples: Input: str = "100100" Output: 2 22 = 4 is the highest power of 2 that divides 36 (100100).Input: str = "10010" Output: 1 Approach: Starting from the right, count the number of 0s in the binary representation
4 min read
Count of pairs in an array such that the highest power of 2 that divides their product is 1
Given an array arr[] of N positive integers. The task is to find the count of pairs (arr[i], arr[j]) such that the maximum power of 2 that divides arr[i] * arr[j] is 1.Examples: Input: arr[] = {3, 5, 2, 8} Output: 3 (3, 2), (5, 2) and (3, 5) are the only valid pairs. Since the power of 2 that divides 3 * 2 = 6 is 1, 5 * 2 = 10 is 1 and 3 * 5 = 15 i
6 min read
Highest power of 2 that divides the LCM of first N Natural numbers.
Given a number N, the task is to find the largest power of 2 that divides LCM of first N Natural numbers. Examples: Input: N = 5Output: 2Explanation:LCM of {1, 2, 3, 4, 5} = 6060 is divisible by 22 Input: N = 15 Output: 3Explanation:LCM of {1, 2, 3.....14, 15} = 360360360360 is divisible by 23 Naive Approach: The idea is to find the Least common mu
8 min read
Find two co-prime integers such that the first divides A and the second divides B
Given two integers A and B, the task is to find two co-prime numbers C1 and C2 such that C1 divides A and C2 divides B.Examples: Input: A = 12, B = 16 Output: 3 4 12 % 3 = 0 16 % 4 = 0 gcd(3, 4) = 1Input: A = 542, B = 762 Output: 271 381 Recommended: Please try your approach on {IDE} first, before moving on to the solution.Naive approach: A simple
7 min read
Count of triplets (a, b, c) in the Array such that a divides b and b divides c
Given an array arr[] of positive integers of size N, the task is to count number of triplets in the array such that a[i] divides a[j] and a[j] divides a[k] and i &lt; j &lt; k.Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 3 Explanation: The triplets are: (1, 2, 4), (1, 2, 6), (1, 3, 6).Input: arr[] = {1, 2, 2} Output: 1 Explanation: The tripl
8 min read
Find maximum power of a number that divides a factorial
Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact). Examples: Input : fact = 5, n = 2 Output : 3 Explanation: Value of 5! is 120. The largest power of 2 that divides 120 is 8 (or 23 Input : fact = 146, n = 15 Output : 35 The idea is based on Legendre’s formula which finds largest power of a prime numbe
12 min read
Count subarrays where second highest lie before highest
Given an array of N distinct element of at least size 2. A pair (a, b) in an array is defined as 'a' is the index of second highest element and 'b' is the index of highest element in the array. The task is to count all the distinct pair where a &lt; b in all the subarrays. Examples : Input : arr[] = { 1, 3, 2, 4 } Output : 3 Explanation : The subar
9 min read
Count array elements whose highest power of 2 less than or equal to that number is present in the given array
Given an array arr[] consisting of N positive integers, the task is to find the number of array elements whose highest power of 2 less than or equal to that number is present in the array. Examples: Input: arr[] = {3, 4, 6, 9}Output: 2Explanation:There are 2 array elements (4 and 6), whose highest power of 2 is less than it (i.e. 4) are present in
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg