[英]What's the time complexity for the following python function?
def func(n):
if n == 1:
return 1
return func(n-1) + n*(n-1)
print func(5)
Getting confused. 感到困惑。 Not sure what exactly it is. 不确定到底是什么。 Is it O(n)
? 是O(n)
吗?
Calculating the n*(n-1)
is a fixed time operation. 计算n*(n-1)
是固定时间的操作。 The interesting part of the function is calling func(n-1)
until n
is 1
. 该函数有趣的部分是调用func(n-1)
直到n
为1
为止。 The function will make n
such calls, so it's complexity is O(n)
. 该函数将进行n
此类调用,因此其复杂度为O(n)
。
If we assume that arithmetic operations are constant time operations (and they really are when numbers are relatively small) then time complexity is O(n)
: 如果我们假设算术运算是恒定时间运算(并且实际上是在数字相对较小的时候),那么时间复杂度为O(n)
:
T(n) = T(n-1) + C = T(n-2) + C + C = ... = n * C = O(n)
But the multiplication complexity in practice depends on the underlying type (and we are talking about Python where the type depends on the value). 但是实际中乘法的复杂度取决于底层类型(而我们谈论的是Python取决于类型的值)。 It depends on the N
as N
approaches infinity. 当N
接近无穷大时,它取决于N
Thus, strictly speaking, the complexity is equal to: 因此,严格来说,复杂度等于:
T(n) = O(n * multComplexity(n))
And this multComplexity(n)
depends on a specific algorithm that is used for multiplication of huge numbers. 并且此multComplexity(n)
取决于用于大数乘法的特定算法。
As described in other answers, the answer is close to O(n)
for practical purposes. 如其他答案中所述,出于实用目的,答案接近O(n)
。 For a more precise analysis, if you don't want to make the approximation that multiplication is constant-time: 为了进行更精确的分析,如果您不想近似地认为乘法是恒定时间的:
Calculating n*(n-1)
takes O(log n * log n)
(or O(log n)^1.58
, depending on the algorithm Python uses, which depends on the size of the integer). 计算n*(n-1)
需要O(log n * log n)
(或O(log n)^1.58
,取决于Python使用的算法,该算法取决于整数的大小)。 See here - note that we need to take the log
because the complexity is relative to the number of digits. 请参阅此处 -请注意,由于复杂度与位数有关,因此我们需要log
。
Adding the two terms takes O(log n)
, so we can ignore that. 将两个项相加需要O(log n)
,所以我们可以忽略它。
The multiplication gets done O(n)
times, so the total is O(n * log n * log n)
. 乘法完成O(n)
次,因此总数为O(n * log n * log n)
。 (It might be possible to get this bound tighter, but it's certainly larger than O(n)
- see the WolframAlpha plot ). (可能有可能使此约束更严格,但它肯定大于O(n)
-请参见WolframAlpha图 )。
In practice, the log
terms won't really matter unless n
gets very large. 实际上,除非n
很大,对log
项才真正重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.