For each of the following six program fragments: a) Give an analysis of the running time (Big-Oh will do). b) Implement the code in the language of your choice, and give the running time for several values of N. c) Compare your analysis with the actual running times. (1) sum

Answer :

akindeleot

Answer:

1) no of computations are :

sum =0 - (1 time )

i=0 ( 1 times)

i<n ( n times )

++sum(n times)

++i (n times)

Total = 3n+2

O(n) is the big O notation

2) no of computations are :

sum =0 - (1 time )

i=0 ( 1 times)

i<n ( n times )

++sum(n^2 times)

++i (n times)

j=0 ( n times)

j<n (n^2 times)

++j (n^2 times)

Total = 3n^2 + 3n+2

O(n^2) is the big O notation as we considered the maximum possible computation

3) no of computations are :

sum =0 - (1 time )

i=0 ( 1 times)

i<n ( n times )

++sum(n^3 times)

++i (n times)

j=0 ( n times)

j<n (n^3 times)

++j (n^3 times)

Total = 3n^3 + 3n+2

O(n^3) is the big O notation as we considered the maximum possible computation

4) no of computations are :

sum =0 - (1 time )

i=0 ( 1 times)

i<n ( n times )

++i (n times)

In the "j" th loop

j=0 ( n times)

j<i (this executes for max of n^2 times when i=n-1)

Similarly ++j (n^2 times when i=n-1)

Hence ++sum(n^2 times)

Total = 3n^2+ 3n+2

O(n^2) is the big O notation as we considered the maximum possible computation

6) no of computations are :

sum =0 - (1 time )

i=0 ( 1 times)

i<n ( n times )

++i (n times)

In the "j" th loop

j=0 ( n times)

j<i*i(this executes for max of n^3 times when i=n-1)

Similarly ++j (n^3 times when i=n-1)

In the "k" th loop

k=0 ( max of n^3 times when j=n^3)

k<j(max of n^4 times when j=n^3)

Similarly ++k(max of n^4 times when j=n^3)

Finally ++sum ( n^4 times when j=n^3)

Total = 3n^4+ 3n^3+3n+2

O(n^4) is the big O notation as we considered the maximum possible computation

5) no of computations are :

sum =0 - (1 time )

i=0 ( 1 times)

i<n ( n times )

++i (n times)

In the "j" th loop

j=0 ( n times)

j<i*i(this executes for max of n^3 times when i=n-1)

Similarly ++j (n^3 times when i=n-1)

In the "k" th loop

k=0 ( max of n^3 times when j=n^3)

k<j(max of n^4 times when j=n^3)

Similarly ++k(max of n^4 times when j=n^3)

Finally ++sum ( n^4 times when j=n^3)

Total = 3n^4+ 3n^3+3n+2

O(n^4) is the big O notation as we considered the maximum possible computation

Other Questions