Finding nearest power of 2
Performance

What's the next power of 2 smaller than this number (binary presentation)?

0b00100101010010011


It's all the 1's reset except the first:

0b00100000000000000


What's the next power of 2 greater? It's smaller number shifted to left:

0b01000000000000000


The implementation of this logic will be both faster and simpler.

However, be mindful of the special cases when the target number is exactly a power of 2 or zero.

else if

This didn't work on my computer:


if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
else if (n - y) &lt; (x - n)
    puts "#{y} is the closest power of 2 to #{n}."
else
    puts "#{x} is the closest power of 2 to #{n}."
end



I had to change the else if to elsif.

Don't repeat yourself

Instead of this:


if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
elsif (n - y) &lt; (x - n)
    puts "#{y} is the closest power of 2 to #{n}."
else
    puts "#{x} is the closest power of 2 to #{n}."
end



It would be better to reduce the duplication in the printing:

if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
else
    if (n - y) &lt; (x - n)
        result = y
    else
        result = x
    end
    puts "#{result} is the closest power of 2 to #{n}."
end