求助:计算两个嵌套循环算法的时间复杂度(大O表示)
Hey there! Let's break down these two algorithms and figure out what's going on with their time complexity, since your initial O(n⁵) guess doesn't quite match the runtime behavior you're seeing (but there's a good reason for that!).
First, Let's Look at the Two Algorithms
Algorithm 1
sum = 0; for( i=1; i<n; i++ ) for( j=0; j<i*n; j++ ) for( k=0; k<j; k++) sum++;
Algorithm 2
sum = 0; for( i=1; i<n; i++ ) for( j=1; j<i*n; j++ ) if( j%1 == 0 ) for( k=0; k<j; k++ ) sum++;
A Quick Note on Algorithm 2
First off, that if(j%1 == 0) check is a red herring—every integer modulo 1 is 0, so this condition is always true. That means Algorithm 2 behaves exactly like Algorithm 1, which is why their runtimes are nearly identical. No surprises there!
Calculating the Time Complexity
Let's walk through the math step by step, focusing on asymptotic behavior (how the runtime grows as n gets very large—constants and small terms don't matter for big-O notation).
Outer Loop:
iruns from 1 to n-1. For large n, this is roughlyniterations.Middle Loop: For each
i,jruns from 0 toi*n - 1(or 1 toi*n -1in Algorithm 2—again, the +1/-1 doesn't matter for large n). That'si*niterations per outer loop step.Inner Loop: For each
j,kruns from 0 toj-1, which isjiterations. To find the total inner loop operations per outer loop step, we sumjfrom 0 toi*n -1:
$$\sum_{j=0}^{i n -1} j = \frac{(i n -1) \cdot i n}{2} \approx \frac{i^2 n^2}{2}$$
We can ignore the-1here because it's negligible compared toi*nwhen n is large.Total Operations: Now we sum that value over all
ifrom 1 to n-1:
$$\sum_{i=1}^{n-1} \frac{i^2 n^2}{2} = \frac{n^2}{2} \sum_{i=1}^{n-1} i^2$$
The sum of squares formula $\sum_{i=1}^k i^2 = \frac{k(k+1)(2k+1)}{6}$ simplifies to roughly $\frac{n^3}{3}$ when k = n-1 (we only care about the highest-order term).Final Asymptotic Result: Plugging that back in, we get:
$$\frac{n^2}{2} \cdot \frac{n^3}{3} = \frac{n^5}{6}$$Since big-O notation ignores constant factors, this means the time complexity is O(n⁵).
Why Your Runtime Observations Make Sense
- Difference from "pure" O(n⁵) algorithms: If you're comparing to a 5-level nested loop where each level runs exactly
ntimes (e.g.,for (a=0;a<n;a++) for (b=0;b<n;b++) ...), that algorithm does exactlyn⁵operations. Your algorithms only do ~n⁵/6operations—so they're about 6x faster! But big-O doesn't care about constants, so both are still O(n⁵). - Clear difference from O(n⁴) algorithms: When n gets large, n⁵ grows way faster than n⁴. For example, if n=100, n⁵ is 100x larger than n⁴. That's why you see a huge runtime gap between these algorithms and any O(n⁴) implementation.
内容的提问来源于stack exchange,提问作者Hassan Ashas




