Spring 2022 - ECCE342/COSC310 Data Structures/ and Algorithms Quiz 1: Complexity of algorithms Wednesday 16/02/2022 - 13:30-13:50 (20 minutes) Dr. Jamal Zemerly Name ____________________ ID______________ Q1: Calculate the complexity of the following functions in terms of complete derivation of time complexity T(n) and Big-Oh notation. [50 marks] a) public int power(int a, int n ){ //assume that n is a positive integer to calculate an if (n = = 0) return 1; // 2 [1] else if (n = = 1) return a; //1 from if + 2 [2] else return a * power(a, n - 1 ); // 2 from if and else + 3 + T(n-1) [3] } T(n) = 5+T(n-1) = 5+5+T(n-2) = 5+5+5+T(n-3) [4] Let k=3 when n-k=1recursivity stops and k=n-1 [1] T(n) = 5k + T(1) = 5n – 5 + 3 = 5n-2 [4] O(n) [15] b) public void triangular_sum(int n, int a[]) { for(int i=0; i<n-1; i++) { //1+2n+n [2] int sum=0; //n [0.5] for(int j=0; j<i+1; j++) //n+2*n^2/2+n^2/2 [3] sum += i*i + j*j; //5*n^2/2 [2.5] a[i]=sum; //2n [1] } } T(n)= 1+7n+4n2 [1] O(n2)[10] [30 marks] Q2: Given that 2 algorithms have the following time and space complexities: 3/2 A1 time = 3n + 4n - 200 A2 time = 10 n log n+ 400 n A1 space = 4n + 12 A2 space = 3 n2 + 5 a. Give the Big-Oh notation of each algorithm A1(t)=O(n3/2), A1(s)= O(n) A2(t)=O(n log n), A2(s)=O(n2) [12] b. Which one is better in terms of time complexity? A2 [2] c. Which one is better in terms of space complexity? A1 [1] d. For what integer value(s) of n will the worst algorithm in space complexity perform better than the best algorithm? [15] A1 space = 4n + 12 A2 space = 3 n2 + 5 2 When 3 n + 5< 4n + 12 At n=0 5<12 At n=1 8<16 At n=2 17<20At n=3 32>24 so n<3 [15] Q3: Explain the difference between NP and Intractable algorithms giving one example from each type from the problems solved in the lab. Are all intractable problems nondeterministic? Explain why. [20 marks] NP algorithms are non-deterministic polynomial problems which use guessing and backtracking. E.g. N*N Queens [10] Intractable problems include exponential algorithms like Tower of Hanoi which are deterministic but also include all NP problems. [10]