Time complexity of nested loops Dominant term with








- Slides: 8

Time complexity of nested loops • Dominant term with constant: (N 2 lg. M)/6 Values of t: 0, 3, 6, 9, …, tlast≤i , use t = 3 e with Values of e: 0, 1, 2, 3, …, p => tlast=i=3 p => p=i/3 => Values of e: 0, 1, 2, 3, …, i/3. (e has consecutive values) Change of variable: Replace t with e in summation over t Values of k: 1, 2, 4, 8, …, klast≤M , use k = 2 e with Values of e: 0, 1, 2, 3, …, p => klast=M= 2 p => (apply lg in both sides) => p=lg. M => Values of e: 0, 1, 2, 3, …, lg. M. (e has consecutive values) Change of variable: Replace k with e in summation over k We do not need a change of variable for i because values of i are already ‘good’ (consecutive numbers starting at 1) 1

Steps for computing the time complexity of loops: • 2

Time complexity of nested loops • Dominant term with constant: (N 3 M)/12 Values of t: 0, 4, 8, 12, …, tlast<N , use t = 4 e with Values of e: 0, 1, 2, 3, …, p => tlast=N=4 p => p=N/4 => Values of e: 0, 1, 2, 3, …, N/4. (e has consecutive values) Change of variable: Replace t with e in summation over t (Note that even though the loop has t<N, we use tlast = N to solve for p, since we do not need the exact count) 3

Useful processing of summation techniques (for Θ or dominant term calculations) Note that some of these will NOT compute the EXACT solution for the summation • 4

Formula for values of i and exact calculation of number of loop iterations – Example 1 for (i=0; i<=N; i=i+3) printf("A"); • e i=3 e 0 0 1 3 2 6 3 9 … … e 3 e … … p 5

Formula for values of i and exact calculation of number of loop iterations – Example 2 for (i=2; i<=N; i=i+3) printf("A"); • e i=2+3 e 0 2 1 5 2 8 3 11 … … e i = 2+3 e … … p ilast <=N (ilast =2+3 p) 6

Formula for values of i and exact calculation of number of loop iterations – Example 3 for (i=1; i<=N; i=i*5) printf("A"); • e i=5 e 0 1 1 5 2 25 3 125 … … e i=5 e … … p 7

Time complexity of nested loops (small variation of the first example) • Dominant term with constant: (N 2 lg. M)/6 Values of t: 0, 3, 6, 9, …, tlast≤i , use t = 3 e with Values of e: 0, 1, 2, 3, …, p => tlast=i 2=3 p => p=i 2/3 => Values of e: 0, 1, 2, 3, …, i 2/3. (e has consecutive values) Change of variable: Replace t with e in summation over t Values of k: 1, 2, 4, 8, …, klast≤M , use k = 2 e with Values of e: 0, 1, 2, 3, …, p => klast=M= 2 p => (apply lg in both sides) => p=lg. M => Values of e: 0, 1, 2, 3, …, lg. M. (e has consecutive values) Change of variable: Replace k with e in summation over k We do not need a change of variable for i because values of i are already ‘good’ (consecutive numbers starting at 1) 8