[英]What is the time complexity for this algorithm?
public static void Comp(int n)
{
int count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=1;k<n;k*=2)
{
count++;
}
}
}
System.out.println(count);
}
Does anyone knows what the time complexity is? 有谁知道时间的复杂度是多少?
And what is the Big Oh() 什么是大Oh()
Please can u explain this to me, step by step? 请您逐步向我解释一下吗?
The time complexity is O(n^2 log n)
. 时间复杂度为
O(n^2 log n)
。 Why? 为什么? each for-loop is a function of
n
. 每个for循环都是
n
的函数。 And you have to multiply by n for each for loop; 对于每个for循环,您都必须乘以n; except the inner loop which grows as log n.
除了作为log n增长的内部循环。 why?
为什么? for each iteration k is multiplied by 2. Think of merge sort or binary search trees.
对于每次迭代,k都将乘以2。考虑合并排序或二叉搜索树。
details 细节
for the first two loops: summation of 1 from 0 to n, which is n+1 and so the first two loops give (n+1)*(n+1)= n^2+2n+1= O(n^2)
对于前两个循环:1从0到n的和,即n + 1,因此前两个循环给出
(n+1)*(n+1)= n^2+2n+1= O(n^2)
for the k loop, we have k growing as 1,2,4,8,16,32,... so that 2^k = n. 对于k循环,我们有k增长为1,2,4,8,16,32,...,因此2 ^ k = n。 Take the log of both sides and you get
k=log n
取双方的对数,您将得到
k=log n
Again, not clear? 同样,不清楚吗?
So if we set m=0
, and a=2
then we get -2^n/-1
why is a=2? 因此,如果我们将
m=0
设置m=0
a=2
那么我们得到-2^n/-1
为什么a = 2? because that is the a value for which the series yields 2,4,8,16,...2^k 因为那是一个值,该序列可得出2,4,8,16,... 2 ^ k
In theory this is O(n^2 * log(n))
. 理论上,这是
O(n^2 * log(n))
。
Each of two outer loops is O(n)
and the inner one is O(log(n))
, because log base 2
of n
is the number of times which you have to divide n
by 2
to get 1
. 两个外部循环中的每个循环均为
O(n)
,内部两个循环为O(n)
O(log(n))
,因为n
的对数以log base 2
为log base 2
是您必须将n
除以2
才能得到1
。
Also this is a strict bound, ie the code is also Θ(n^2 * log(n))
这也是一个严格的界限,即代码也是
Θ(n^2 * log(n))
Whoever gave you this problem is almost certainly looking for the answer n^2 log(n)
, for reasons explained by others. 谁给您这个问题,几乎可以肯定是在寻找答案
n^2 log(n)
,这是由其他人解释的原因。
However the question doesn't really make any sense. 但是,这个问题实际上没有任何意义。 If
n > 2^30
, k
will overflow, making the inner loop infinite. 如果
n > 2^30
,则k
将溢出,从而使内部循环变为无限。
Even if we treat this problem as being completely theoretical, and assume n
, k
and count
aren't Java int
s, but some theoretical integer type, the answer n^2 log n
assumes that the operations ++
and *=
have constant time complexity, no matter how many bits are needed to represent the integers. 即使我们将这个问题完全视为理论问题,并假设
n
, k
和count
不是Java int
s,而是某种理论上的整数类型,答案n^2 log n
假定++
和*=
操作具有恒定时间复杂度,无论需要多少位来表示整数。 This assumption isn't really valid. 这个假设不是真的成立。
It has been pointed out to me in the comments below that, based on the way the hardware works, it is reasonable to assume that ++
, *=2
and <
all have constant time complexity, no matter how many bits are required. 有人向我指出在下面的意见,基于硬件的工作方式,这是合理的假设,
++
, *=2
和<
都有固定的时间复杂度,无论需要多少位。 This invalidates the third paragraph of my answer. 这使我的答案的第三段无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.