What would be the time complexity for this snippet? I'm having a little trouble understanding how to find the time complexity of nested for loops with different conditions.
I originally thought that it would be n^3 xn^2 which gives O(n^5), but should it be (n^3)^2 which gives O(n^6)?
for(int i = 0; i < n*n; i++) {
for(int j = 0; j < n*n*n; j++) {
A(); //O(1)
}
}
If you correctly incremented j
in the inner loop (replacing i++
with j++
in the inner loop increment step), it would be O(n⁵)
. The outer loop runs the inner loop n²
times, with each inner loop running n³
times; the total is strictly multiplicative, n² * n³ == n⁵
.
As written, it'll never stop running if n > 1
(because j
never increments, so if the inner loop begins running, it runs forever).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.