这个表达式是 O(n^2) 还是 O(n^3)?
Sum[(i + 1) (n - i), {i, 0, n - 1}]
是 ( i+1)(n-1) 的总和,范围从 i=0 到 n-1。
是 O(n^2) 还是 O(n^3)? 你能解释一下你是如何找到它的吗?谢谢。
Sum[(i + 1) (n - i), {i, 0, n - 1}]
that is a sum of ( i+1)(n-1) with bounds from i=0 to n-1.
is that O(n^2) or O(n^3)?
and can you explain me how you found it? thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
展开并使用 sum(i^k) 的封闭式表达式。也就是说,
在
“省略细节”步骤中,将每个和展开为其封闭式表达式,并注意
n^3
的系数不为零(它是1 / 6< /代码>)。
Expand and use the closed-form expressions for sum(i^k). To wit,
so that
In the step "details elided", expand each sum to its closed-form expression and note that the coefficient of
n^3
is not zero (it's1 / 6
).如果您谈论的是评估总和所需的时间,那么它是 O(1) (因为它可以简化为封闭式公式)。如果你谈论的是公式本身,那么将其展开并代入幂和,你会发现 n^3(最高次)的系数不为 0。
无论如何,O(n^2)是 O(n^3) 的子集,所以...当询问它是 O(n^2) 还是 O(n^3) 时,一个简单的答案是它是 O(n^3) (如果你知道答案永远不能是“两者都不是”)。
If you are talking about the time needed to evaluate the sum, then it is O(1) (because it can be reduced to a closed-form formula). If you are talking about the formula itself, then expand it and substitute the power sums, and you'll see that the coefficient of n^3 (which is of the highest degree) is not 0.
Anyway, O(n^2) is a subset of O(n^3), so... when asking is it O(n^2) or O(n^3), an easy answer is it is O(n^3) (if you know the answer can never be "neither").
Wolfram|Alpha 午餐吃这些:
http://www.wolframalpha.com/input/?i=Sum%5B(i+%2B+1)+(n+-+i ),+%7Bi,+0,+n++1%7D%5D
Wolfram|Alpha eats these for lunch:
http://www.wolframalpha.com/input/?i=Sum%5B(i+%2B+1)+(n+-+i),+%7Bi,+0,+n+-+1%7D%5D