Write a function to take a positive integer and return the largest power of two less than or equal to this integer – JavaScript Program.

 

A function that takes a positive integer and returns the largest power of two less than or equal to that integer.


Input: 5

Output: 4

 

Input: 16

Output: 16

 

Input: 10

Output: 8


 

Code:

function nearest_power_of_two(n) {
    let num = 1
    for (let i = 1; i < 100; i++) {
        if (num * 2 > number){
            break
        }
        else{
            num = num * 2
        }
    }
    return num
}

console.log("Answer is: " + nearest_power_of_two(5));

 

Output:

Answer is: 4

 

This code can be written as: In ES6  Syntax

const nearest_power_of_two = n => {
    let num = 1
    for (let i = 1; i < 100; i++) {
        if (num * 2 > number) break
        else num = num * 2
    }
    return num
}

console.log("Answer is: " + nearest_power_of_two(9));

 

The logic behind this code:

Declare a variable num with the value of 1. A loop will execute 99 times and calculate the power.

When the power is less than or equal to the given number, the variable num will overwrite by num * 2 and, if power is greater than the number then the loop will stop executing.

Finally, the function will return the variable num which stores the last value of power 2.

Leave a Reply

Your email address will not be published.