[英]What is the run time complexity of this for loop?
I am trying to find out the run-time complexity of this algorithm. 我试图找出此算法的运行时复杂性。
public static void main(String[] args) throws InterruptedException{
for (int N=100; N<=1000000; N=N*5) {
long start = System.currentTimeMillis();
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= Math.pow(N,1.5); j++) {
i = i*2;
j = j*2;
Thread.sleep(10);
}
}
long stop = System.currentTimeMillis();
long elapsed = (long)(stop - start);
System.out.println();
System.out.println("For N=" + N + " RT in msec: "+elapsed);
}
}
The first for loop: 第一个for循环:
for (int N=100; N<=1000000; N=N*5) // runs n/5 times, so O(n).
The first inner loop: 第一个内部循环:
for (int i = 1; i <= N; i++) // runs n times.
The second inner loop: 第二个内部循环:
for (int j = 1; j <= Math.pow(N,1.5); j++) { // we can consider Math.pow O(1)
i = i*2;
j = j*2;
Thread.sleep(10);
}
So by multiplying all O(n) * O(n) * O(1) = O(n^2) Is my answer correct? 因此,通过将所有O(n)* O(n)* O(1)= O(n ^ 2)相乘,我的答案正确吗? I am a little confused on this. 我对此有些困惑。 Will appreciate any clarification on this. 将不胜感激对此任何澄清。 Thank You 谢谢
The first loop is actually O(k)
which 5^k = N
. 第一个循环实际上是O(k)
,其中5^k = N
Hence, k = log_5(N)
. 因此, k = log_5(N)
。 The first inner loop is true (in O(n)
). 第一个内部循环为true(在O(n)
)。 And the second inner loop j
is each time is times to 2
. 第二个内部循环j
每次是2
。 Hence, it is O(h)
which 2^h = N^1.5
. 因此,是O(h)
2^h = N^1.5
。 Therefore, h = 1.5 log(N)
. 因此, h = 1.5 log(N)
。
In sum, the algorithm is in O(log_5(N) * N * log(N)) = O(N log^2(N))
. 总之,该算法为O(log_5(N) * N * log(N)) = O(N log^2(N))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.