我可以用Binet公式,即闭解公式,在一个固定的时间内,计算任何通常可计算的fibonnaci数(除非结果变得很大)。这是我的代码:
对于fibonnaci的非递归实现:
gr = (1 + 5**0.5) / 2
def gfib(n):
return int(((gr**n - (1-gr)**n) / 5**0.5))
我知道a^n表示指数级的运行时复杂性,但是当代码在python中运行时,情况并非如此,因为这会立即计算第n个fibonnaci数。我做了一些关于指数在python中如何实现的研究(可能是通过平方来求幂?)给出常数时间解,但还没有找到一个明确的答案。有什么想法吗?在
float.__pow__()方法使用C的libm,它充分利用了硬件对二进制浮点运算的支持。后者用对数表示数字。对数表示使实现指数化仅仅是一次乘法成为可能。在
执行摘要:浮点指数在硬件中实现,由于对数的魔力,它几乎以恒定速度运行。在
您可以在CPython的source code for the log_pow function找到实现。在
整数的指数可以比你想象的更有效地计算。以下是Wikipedia has to say about it:
平方求幂这一页很难总结,但它基本上是2⁸==(2⁴)²==(2²)²,所以不需要计算
2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 256
,而是可以计算2 × 2 = 4; 4 × 4 = 16; 16 × 16 = 256
。在相关问题 更多 >
编程相关推荐