Solutions Homework 1 1. Solution 1. Notice that for any value of j and k, i iterates k − j + 1 times. So given a specific value of j, since k goes from j to n, the number of times i iterates is 1 + 2 + · · · + (n − j + 1) = (n − j + 1)(n − j + 2) (n − j + 1)(n − j) ≥ 2 2 So total number of iterations ≥ n X (n − j + 1)(n − j + 2) 2 j=1 n 1X 2 = (n + n) − (2n + 1)j + j 2 2 j=1 n(n + 1) n(n + 1)(2n + 1) 1 2 + n(n + n) − (2n + 1) = 2 2 6 2 n(n − 1) = 6 Now set n(n2 − 1) ≥ cn3 6 and solve this inequality for n. We get 1 n≥ √ . 1 − 6c Therefore, if we let c = 1/12 and n0 = 2, we have that total number of iterations ≥ cn3 whenever n ≥ n0 . So the runtime is Ω(n3 ). Solution 2. We have total number of iterations = n X n X k X 1 j=1 k=j i=j ≥ n/3 2n/3 n X X X 1 j=1 k=2n/3 i=n/3 ≥ n3 . 27 Therefore, if we let c = 1/27 and n0 = 1, we have that total number of iterations ≥ cn3 whenever n ≥ n0 . So the runtime is Ω(n3 ). 1 Solutions Homework 1 Solution 3. Notice that the pseudocode iterates through all possible triplets (j, i, k) such that j ≤ i ≤ k and such i, j, k each has a value between 1 and n. If we have ignore the duplicate values such as (2, 2, 3), then the total number of such triplets is n n(n − 1)(n − 2) = . 3 6 Set n(n − 1)(n − 2) ≥ cn3 . 6 Let c = 1/12. This simplifies to n2 − 6n + 4 ≥ 0 Now it’s easy to see that this inequality holds for all n ≥ 6. Therefore, if we let c = 1/12 and n0 = 6, we have that total number of iterations ≥ cn3 whenever n ≥ n0 . So the runtime is Ω(n3 ). 2. If n0 = 59, then 10n log n < n2 whenever n ≥ n0 . 3. All answers below are approximate. 1 Second log n 10300000 √ n 1012 n 106 n log n 6 × 104 n2 103 n3 102 n 2 20 n! 9 1 Hour 9 1010 2 × 1019 4 × 109 108 6 × 104 2 × 103 32 12 1 Month 11 109×10 9 × 1024 3 × 1012 8 × 1010 2 × 106 2 × 104 41 15 1 Century 14 109×10 9 × 1030 3 × 1015 7 × 1013 5 × 107 2 × 105 51 17 4. reverse(A): s = stack() for i from 1 to len(A): s.push(A[i]) for i from 1 to len(A): A[i] = s.pop() The running time is 2n or O(n). 2
© Copyright 2026 Paperzz