Open In App

JavaScript Program to Find the Next Power of Two

Last Updated : 14 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive integer, find the next power of two greater than the given number using JavaScript.

Examples: 

Input: N = 6
Output: 8
Explanation: The next power of two greater than 6 is 8.

Input: N = 16
Output: 16
Explanation: 16 is already a power of two, so the next power of two is also 16.

Below are the approaches to finding the Next Power of Two which are as follows:

1. Using Bit Manipulation

In this approach, we use bitwise operations to find the next power of two. We start by checking if the given number is already a power of two. If it is, we simply return the number itself. Otherwise, we iteratively left shift the number until it becomes a power of two. Each left shift effectively multiplies the number by 2, incrementing the power count. Once we've completed the left shifts, we return 2 raised to the power count, which gives us the next power of two.

Example: Implementation of program to find the Next Power of Two using Bit Manipulation

JavaScript
function nextPower(n) {
    let count = 0;
    // If the given number is 
    // already a power of two, return it
    if ((n & (n - 1)) === 0) {
        return n;
    }
    // Left shift the number 
    // until it becomes a power of two
    while (n > 0) {
        n >>= 1;
        count++;
    }
    return 1 << count;
    // Return the next power of two
}

const num = 15;
console.log("Next power of two:", nextPower(num));

Output
Next power of two: 16

Time Complexity: O(Log n)

Auxiliary Space: O(1)

2. Using Math Functions

In this approach, we use mathematical functions to determine the next power of two. We first calculate the logarithm base 2 of the given number, which effectively gives us the exponent of the next power of two. To ensure that we obtain the next integer value higher than this exponent, we round up the result to the nearest integer using the ceiling function. Finally, we raise 2 to this power to obtain the next power of two.

Example: Implementation of program to the Next Power of Two using Math Functions

JavaScript
function nextPower(n) {
    const power = Math
        .ceil(Math.log2(n));
    // Return 2 raised to this power
    return 2 ** power;
}

const num = 15;
console.log("Next power of two:", nextPower(num));

Output
Next power of two: 16

Time Complexity: O(1)

Auxiliary Space: O(1)

3. Using loop

In this approach we use a while loop to continuously double a number until it becomes equal to the input number.

Example: Implementation of program to the Next Power of Two using while loop.

JavaScript
function nextPowerOfTwo(num) {
    let result = 1;
    while (result < num) {
        result *= 2;
    }
    return result;
}

console.log(nextPowerOfTwo(15));

Output
16

Time Complexity: O(log n) - where n is the input number

Space Complexity: O(n)


Next Article

Similar Reads