这个c函数的复杂度是多少
以下 c 函数的复杂度是多少?
double foo (int n) {
int i;
double sum;
if (n==0) return 1.0;
else {
sum = 0.0;
for (i =0; i<n; i++)
sum +=foo(i);
return sum;
}
}
请不要只是发布复杂性,你能帮助我理解如何去做吗?
编辑:这是考试中提出的客观问题,提供的选项是 1.O(1) 2.O(n) 3.O(n!) 4.O(n^n)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是 θ(2^n)(假设 f 是我们算法的运行时间):
实际上,如果我们忽略常量操作,则确切的运行时间是 2n。
另外,在您写的这是一次考试的情况下,O(n!) 和 O(n^n) 都是正确的,其中最接近 θ(2^n) 的答案是 O(n!),但如果我是学生,我会标记它们两个:)
O(n!) 的解释:
It's Θ(2^n) ( by assuming f is a running time of algorithm we have):
Actually if we ignore the constant operations, the exact running time is 2n.
Also in the case you wrote this is an exam, both O(n!) and O(n^n) are true and nearest answer to Θ(2^n) among them is O(n!), but if I was student, I'll mark both of them :)
Explanation on O(n!):
其一,它的编码很差:)
您调用 foo() 的次数总共类似于 n^n (将 n 向下舍入到最接近的整数),
例如:
foo(3) 将被调用 3^3 次。
祝你好运,圣诞快乐。
编辑:哎呀,刚刚更正了一些内容。为什么 foo 返回双精度值?它将始终返回一个整数,而不是双精度数。
这将是一个更好的版本,带有微优化! :D
For one, it is poorly coded :)
You're calling foo() a total of something like n^n (where you round n down to the nearest integer)
e.g.:
foo(3)will be called 3^3 times.
Good luck, and merry Christmas.
EDIT: oops, just corrected something. Why does foo return a double? It will always return an integer, not a double.
Here would be a better version, with micro-optimizations! :D
你本来可以更清楚一点... grumble grumble
number_of_times_known = pow(2, n-1);
让我们尝试输入输入,好吗?使用此代码:
我们得到:
因此,它可以简化为:
You could have been a bit more clearer... grumble grumble
number_of_times_called = pow(2, n-1);
Let's try putting in inputs, shall we?Using this code:
We get:
Therefore, it can be simplified to:
该函数由多个部分组成。
第一个复杂性是
if(n==0)return 1.0;
,因为它只生成一次运行。那将是O(1)
。下一部分是 for(i=0; i0..n 开始循环,所以它是
O(n)
比有递归,对于
n
中的每个数字,您都运行该函数再次。在该函数中再次循环,以及下一个函数。等等...为了弄清楚它会是什么,我建议您在循环内部添加一个全局计数器,以便您可以看到它针对特定数量执行了多少次。
The function is composed of multiple parts.
The first bit of complexity is the
if(n==0)return 1.0;
, since that only generates one run. That would beO(1)
.The next part is the
for(i=0; i<n; i++)
loop. Since that loops from0..n
it isO(n)
Than there is the recursion, for every number in
n
you run the function again. And in that function again the loop, and the next function. And so on...To figure out what it will be I recommend you add a global ounter inside of the loop so you can see how many times it is executed for a certain number.