Find the next power less than n in Julia

I need to find the next power half the given number in Julia.

i.e. smallerpoweroftwo(15)must return 8, but smallerpoweroftwo(17)must return16

I still have it, but searching on a bit string seems a bit hacked to me. Maybe this is not ... Any ideas?

function smallerpoweroftwo(n::Int)
    2^(length(bits(n)) - search(bits(n), '1'))
end

Thank!

Edit: I basically thought there was a more elegant way to do this, just using bitwise arithmetic. Or is there a bit length function somewhere, like in some other languages?

+3
source share
2 answers

The Julia Standard Library has features prevpow2and nextpow2:

help?> prevpow2
search: prevpow2 prevpow prevprod

  prevpow2(n)

  The largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative
  arguments.

help?> nextpow2
search: nextpow2 nextpow nextprod

  nextpow2(n)

  The smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative
  arguments.

The function prevpow2should do what you want.

+6

? 1

2^floor(Int, log(2,n-1))

1 jverzani.

0

Source: https://habr.com/ru/post/1651577/


All Articles