|
| 1 | +public class Assignment_TC_SC { |
| 2 | + public static void main(String[] args) { |
| 3 | + // Question 1 : Find the Time Complexity of the following: |
| 4 | + // int i, j, k = 0, n; |
| 5 | + // for (i = n / 2; i <= n; i++) { |
| 6 | + // for (j = 2; j <= n; j = j * 2) { |
| 7 | + // k = k + n / 2; |
| 8 | + // } |
| 9 | + // } |
| 10 | + // Option :- |
| 11 | + // A. O(n) |
| 12 | + // B. O(N log N) |
| 13 | + // C. O(n^2) |
| 14 | + // D. O(n^2Logn) |
| 15 | + // Answer :- B = O(n * logn) |
| 16 | + |
| 17 | + // Question 2 : Find the Time Complexity of the following: |
| 18 | + // for(int i=0;i<n;i++) |
| 19 | + // i*=k |
| 20 | + // } |
| 21 | + // Option :- |
| 22 | + // Here, k is some constant value |
| 23 | + // A. O(n) |
| 24 | + // B. O(k) |
| 25 | + // C. O(logkn) (= logn of base k) |
| 26 | + // D. O(lognk) (= logk of base n) |
| 27 | + // Answer :- C = O(logkn) (= logn of base k) |
| 28 | + |
| 29 | + // Question 3 : Algorithm A and B have a worst-case running time of O(n) and O(logn), respectively. Therefore, algorithm B always runs faster than algorithm A. |
| 30 | + // Option :- |
| 31 | + // A. True |
| 32 | + // B. False |
| 33 | + // Answer :- B = false (The Big-O notation provides an asymptotic comparison in the running time of algorithms. For n < n0, algorithm A might run faster than algorithm B, for instance.) |
| 34 | + |
| 35 | + // Question 4 : Find the time & space complexity of floorSqrt function in the following code to calculate square root of a number : |
| 36 | + // static int floorSqrt(int x){ |
| 37 | + // if (x == 0 || x == 1) return x; |
| 38 | + // int i = 1, result = 1; |
| 39 | + // while (result <= x) { |
| 40 | + // i++; |
| 41 | + // result = i * i; |
| 42 | + // } |
| 43 | + // return i - 1; |
| 44 | + // } |
| 45 | + // main function-- |
| 46 | + // int x = 11; |
| 47 | + // System.out.print(floorSqrt(x)); |
| 48 | + // TC -> O(sq root of x) |
| 49 | + // SC -> O(1) |
| 50 | + |
| 51 | + // Question 5 : Find the time & space complexity of the following code: |
| 52 | + // int a = 0; |
| 53 | + // for (int i = 0; i < n; ++i) { |
| 54 | + // for (int j = n; j > i; --j) { |
| 55 | + // a = a + i + j; |
| 56 | + // } |
| 57 | + // } |
| 58 | + // TC -> O(n^2) |
| 59 | + // SC -> O(1) |
| 60 | + |
| 61 | + } |
| 62 | +} |
0 commit comments