In: Computer Science
Solution of 1.
a) For the outermost loop i.e for each i , j varies from 1 to n and for each j , k varies from 1 to n,
Hence, the output will be
n2 times 1 , n2 times 2, n2 times 3, ................. n2 times n
b) Lets say n=2,the numbers present inside the 3d array will be -> 1,1,1,1,2,2,2,2 and the number of assignment operations = 8 = 23
As we can say that for every element of the 3d array, one assignment operation is being performed.
Hence, total number of assignment operations = n3
c)
When j=1, Print operation will be performed n times i.e when k varies from 1 to n.
When j=2, Print operation will be performed n times i.e when k varies from 1 to n.
...........
When j=n, Print operation will be performed n times i.e when k varies from 1 to n.
Similarly the loop goes for i,
When i=1, Print operation will be performed n2 times i.e when j varies from 1 to n and for every j, k varies from 1 to n.
When i=2, Print operation will be performed n2 times i.e when j varies from 1 to n and for every j, k varies from 1 to n.
...........
When i=n, Print operation will be performed n2 times i.e when j varies from 1 to n and for every j, k varies from 1 to n.
Hence, the number of Print operations = n*n*n = n3
)
d) As seen in the example mentioned in section c, the number of assignment operations = n3 and number of Print operations=n3.
Since a single print statement and assignment operations take constant time to be done i.e time taken to perform both the operations i.e O(1) is constant and is independent from the number of elements in the 3d array,
Hence, the time complexity is solely dependent on the number of times the print and assignment operation has been done.
So, time complexity = n3 + n3 = 2n3 = O(n3)
Solution of 2.
a) n2/4 times 1 , n2/4 times 2, n2/4 times 3, ................. n2/4 times n.
b) As described in the section b of the above answer,
total number of assignment operations = n*n/2*n/2 = n3/4
c) As described in the section c of the above answer,
number of Print operations = n*n/2*n/2 = n3/4
d) With the same logic as discussed in section c of the above answer,
time complexity = n3/4 + n3/4 = n3/2 = O(n3)
Solution of 3.
a) n2/16 times 1 , n2/16 times 2, n2/16 times 3, ................. n2/16 times n.
b) As described in the section b of the above answer,
total number of assignment operations = n*n/4*n/4 = n3/16
c) As described in the section c of the above answer,
number of Print operations = n*n/4*n/4 = n3/16
d) With the same logic as discussed in section c of the above answer,
time complexity = n3/16 + n3/16 = n3/8 = O(n3)