Homework Answers
Homework Answers
Answer the following questions. You can write your answers in English or Azerbaijani.
6.A:
void homework_A(int n)
{
int i=0, j=0, k=0, home=1, n = 10000;
for (i= n/2; i<=n; i++)
for (j= 1; j <= n; 2*j)
for (k= 1; k <=n; k++)
home++;
}
6.B:
void homework_B()
{
int a = 0, b = 0, n = 20000, m=20000;
for (i = 0; i < n; i++)
a = a + rand();
for (j = 0; j < m; j++)
b = b + rand();
}
6.C:
void homework_C()
{
int i, j, a = 0, n = 10000;
for (i = 0; i < n; i++)
for (j = n; j > i; j--)
a = a + i + j;
}
1)data structure is a data organization and storage format that is usually chosen for efficient access to data.
3) Time complexity is a type of computational complexity that describes the time required to execute an algorithm
4) Efficiency – Proper choice of data structure makes the program efficient in terms of space and time.
So, the overall time complexity of the program is O(n² log n).
Since these loops are independent and run one after the other, we just add the time complexities:
6 c) 1. Outer Loop:
The outer loop runs n times (from i = 0 to i < n).So, the time complexity of the outer loop is O(n).
2. Inner Loop:
For each iteration of the outer loop, the inner loop runs from j = n to j > i. So, when i = 0, the inner loop runs n times.When i = 1, the inner loop runs
n - 1 times.When i = 2, it runs n - 2 times, and so on.The number of times the inner loop runs decreases as i increases.
3. Total Iterations:
The total number of iterations is the sum:
n + (n - 1) + (n - 2) + … + 1
This is the sum of the first n numbers, which equals:
n(n+1)/2
So,This simplifies to O(n²).
HOMEWORK PROBLEM
1. Outer Loop (i loop):
The outer loop runs from i = n / 2 to i = n, so it iterates n / 2 times.This is approximately n iterations.Thus, the time complexity of the outer loop is
O(n).
2. Middle Loop (j loop):
The middle loop runs from j = 1 to j <= n, with j being multiplied by 2 each time (j = j * 2).This means j doubles every time (1, 2, 4, 8,
…).Therefore, the loop will run approximately log n times, because the value of j doubles each time until it reaches n.The time complexity of the
middle loop is O(log n).
3. Inner Loop (k loop):
The inner loop runs from k = 1 to k <= n, so it iterates n times.Therefore, the time complexity of the inner loop is O(n).