在朱莉娅找到小于n的两个下一个幂

时间:2016-08-17 16:26:37

标签: julia

我需要在朱莉娅找到小于给定数字的下两个幂。

即。 smallerpoweroftwo(15)应返回8,但smallerpoweroftwo(17)应返回16

到目前为止,我有这个,但搜索一串比特对我来说似乎有些苛刻。也许它不......任何想法?

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

谢谢!

编辑: 我主要想的是使用按位算法有更优雅的方法来做到这一点。或者在某些其他语言中是否存在位长函数?

2 个答案:

答案 0 :(得分:6)

Julia的标准库包含prevpow2nextpow2函数:

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.

prevpow2函数应该做你想要的。

答案 1 :(得分:0)

这个怎么样? 1

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

1 在jverzani评论后将指数添加到解决方案中。

相关问题