分析递归函数(甚至评估它们)是一项不平凡的任务。 (在我看来)很好的介绍可以在 Don Knuths Concrete Mathematics 中找到。
不过,现在让我们分析一下这些例子:
我们定义了一个函数,它为我们提供了函数所需的时间。假设t(n)表示pow(x,n)所需的时间,即n的函数。
那么我们可以得出结论,t(0)=c,因为如果我们调用pow(x,0),我们必须检查是否(n==0),然后返回1,这可以在常数时间内完成(因此常数@987654329 @)。
现在我们考虑另一种情况:n>0。这里我们获得t(n) = d + t(n-1)。那是因为我们必须再次检查n==1,计算pow(x, n-1,因此是(t(n-1)),然后将结果乘以x。校验和乘法可以在常数时间内完成(常数d),递归计算pow需要t(n-1)。
现在我们可以“扩展”术语t(n):
t(n) =
d + t(n-1) =
d + (d + t(n-2)) =
d + d + t(n-2) =
d + d + d + t(n-3) =
... =
d + d + d + ... + t(1) =
d + d + d + ... + c
那么,我们需要多长时间才能到达t(1)?因为我们从t(n)开始,每一步减1,所以需要n-1步才能达到t(n-(n-1)) = t(1)。另一方面,这意味着我们得到n-1 乘以常数d,而t(1) 被评估为c。
所以我们得到:
t(n) =
...
d + d + d + ... + c =
(n-1) * d + c
所以我们得到t(n)=(n-1) * d + c,它是 O(n) 的元素。
pow2 可以使用Masters theorem 完成。因为我们可以假设算法的时间函数是单调递增的。所以现在我们有了计算pow2(x,n)所需的时间t(n):
t(0) = c (since constant time needed for computation of pow(x,0))
对于n>0,我们得到
/ t((n-1)/2) + d if n is odd (d is constant cost)
t(n) = <
\ t(n/2) + d if n is even (d is constant cost)
以上可以“简化”为:
t(n) = floor(t(n/2)) + d <= t(n/2) + d (since t is monotonically increasing)
所以我们得到t(n) <= t(n/2) + d,可以使用t(n) = O(log n)的masters theorem来解决(参见维基百科链接中流行算法的应用部分,例如“二进制搜索”)。