Skip to content
Related Articles

Related Articles

Improve Article

Find the nearest power of 2 for every array element

  • Last Updated : 07 Apr, 2021
Geek Week

Given an array arr[] of size N, the task is to print the nearest power of 2 for each array element. 
Note: If there happens to be two nearest powers of 2, consider the larger one.

Examples:

Input: arr[] = {5, 2, 7, 12} 
Output: 4 2 8 16 
Explanation: 
The nearest power of arr[0] ( = 5) is 4. 
The nearest power of arr[1] ( = 2) is 2. 
The nearest power of arr[2] ( = 7) is 8. 
The nearest power of arr[3] ( = 12) are 8 and 16. Print 16, as it is the largest.

Input: arr[] = {31, 13, 64} 
Output: 32 16 64

Approach: Follow the steps below to solve the problem:



  • Traverse the array from left to right.
  • For every array element, find the nearest powers of 2 greater and smaller than it, i.e. calculate pow(2, log2(arr[i])) and pow(2, log2(arr[i]) + 1).
  • Calculate difference of these two values from the current array element and print the nearest as specified in the problem statement.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find nearest power of two
// for every element in the given array
void nearestPowerOfTwo(int arr[], int N)
{
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Calculate log of the
        // current array element
        int lg = log2(arr[i]);
        int a = pow(2, lg);
        int b = pow(2, lg + 1);
 
        // Find the nearest
        if ((arr[i] - a) < (b - arr[i]))
            cout << a << " ";
        else
            cout << b << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 2, 7, 12 };
    int N = sizeof(arr) / sizeof(arr[0]);
    nearestPowerOfTwo(arr, N);
    return 0;
}

Java




// Java program to implement the above approach
import java.io.*;
 
class GFG {
 
    // Function to find the nearest power of two
    // for every element of the given array
    static void nearestPowerOfTwo(int[] arr, int N)
    {
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Calculate log of the
            // current array element
            int lg = (int)(Math.log(arr[i])
                           / Math.log(2));
 
            int a = (int)(Math.pow(2, lg));
            int b = (int)(Math.pow(2, lg + 1));
 
            // Find the nearest
            if ((arr[i] - a) < (b - arr[i]))
                System.out.print(a + " ");
            else
                System.out.print(b + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 5, 2, 7, 12 };
        int N = arr.length;
        nearestPowerOfTwo(arr, N);
    }
}

Python3




# Python program to implement the above approach
import math
 
# Function to find the nearest power
# of two for every array element
def nearestPowerOfTwo(arr, N):
 
    # Traverse the array
    for i in range(N):
 
        # Calculate log of current array element
        lg = (int)(math.log2(arr[i]))
 
        a = (int)(math.pow(2, lg))
        b = (int)(math.pow(2, lg + 1))
 
        # Find the nearest
        if ((arr[i] - a) < (b - arr[i])):
            print(a, end = " ")
        else:
            print(b, end = " ")
 
 
# Driver Code
arr = [5, 2, 7, 12]
N = len(arr)
nearestPowerOfTwo(arr, N)

C#




// C# program to implement the above approach
using System;
 
class GFG {
 
    // Function to find nearest power of two
    // for every array element
    static void nearestPowerOfTwo(int[] arr, int N)
    {
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Calculate log of the
            // current array element
            int lg = (int)(Math.Log(arr[i])
                           / Math.Log(2));
 
            int a = (int)(Math.Pow(2, lg));
            int b = (int)(Math.Pow(2, lg + 1));
 
            // Find the nearest
            if ((arr[i] - a) < (b - arr[i]))
                Console.Write(a + " ");
            else
                Console.Write(b + " ");
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 5, 2, 7, 12 };
        int N = arr.Length;
        nearestPowerOfTwo(arr, N);
    }
}

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
    // Function to find the nearest power of two
    // for every element of the given array
    function nearestPowerOfTwo(arr , N) {
 
        // Traverse the array
        for (i = 0; i < N; i++) {
 
            // Calculate log of the
            // current array element
            var lg = parseInt( (Math.log(arr[i]) / Math.log(2)));
            var a = parseInt( (Math.pow(2, lg)));
            var b = parseInt( (Math.pow(2, lg + 1)));
 
            // Find the nearest
            if ((arr[i] - a) < (b - arr[i]))
                document.write(a + " ");
            else
                document.write(b + " ");
        }
    }
 
    // Driver Code
     
        var arr = [ 5, 2, 7, 12 ];
        var N = arr.length;
        nearestPowerOfTwo(arr, N);
 
// This code is contributed by todaysgaurav
 
</script>
Output: 
4 2 8 16

 

 

Time Complexity: O(N) 
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :