如何找到与给定输入最接近的 2^N 值?
我必须以某种方式保持程序运行,直到指数函数的输出超过输入值,然后将其与指数函数的先前输出进行比较。即使只是伪代码,我该如何做这样的事情?
I somehow have to keep my program running until the output of the exponent function exceeds the input value, and then compare that to the previous output of the exponent function. How would I do something like that, even if in just pseudocode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
根据您使用的语言,您可以使用按位运算轻松完成此操作。您需要设置的单个 1 位大于输入值中设置的最高一位的值,或者设置为输入值中设置的最高一位的值。
如果您确实将最高设置位以下的所有位设置为 1,则添加 1,最终得到下一个更大的 2 的幂。您可以右移此值以获得下一个较低的二的幂并选择两者中更接近的一个。
请参阅 Bit Twiddling Hacks 了解其他类似的技巧。
Depending on which language you're using, you can do this easily using bitwise operations. You want either the value with a single 1 bit set greater than the highest one bit set in the input value, or the value with the highest one bit set in the input value.
If you do set all of the bits below the highest set bit to 1, then add one you end up with the next greater power of two. You can right shift this to get the next lower power of two and choose the closer of the two.
See Bit Twiddling Hacks for other similar tricks.
除了循环之外,还有一种解决方案可能会更快,具体取决于编译器如何映射 nlz 指令:
没有显式循环,并且肯定比使用 Math.pow 的解决方案更有效。如果不查看编译器为
numberOfLeadingZeros
生成的代码,很难说更多。这样我们就可以轻松获得 2 的较低幂,然后比较哪个更接近 - 在我看来,每个解决方案都必须完成最后一部分。
Apart from the looping there's also one solution that may be faster depending on how the compiler maps the nlz instruction:
No explicit looping and certainly more efficient than the solutions using
Math.pow
. Hard to say more without looking what code the compiler generates fornumberOfLeadingZeros
.With that we can then easily get the lower power of 2 and then compare which one is nearer - the last part has to be done for each solution it seems to me.
将 x 设置为 1。
当 x <目标,设置 x = 2 * x
,然后返回 x 或 x / 2,以更接近目标的为准。
set x to 1.
while x < target, set x = 2 * x
then just return x or x / 2, whichever is closer to the target.
我将使用 5 作为输入,而不是 50。
I will use 5 as input for an easy example instead of 50.
下面是一个函数的伪代码,该函数接受输入数字并返回您的答案。
Here's the pseudo code for a function that takes the input number and returns your answer.
这是一个按位解决方案——如果出现平局,它将返回 2^N 和 2^(N+1) 的减数。与调用 log() 函数相比,这应该非常快
Here's a bitwise solution--it will return the lessor of 2^N and 2^(N+1) in case of a tie. This should be very fast compare to invoking the log() function