Just looking over some past paper and I got a question I seem to be struggling on
Let Z be an array with elements Z(1), Z(2),...,Z(n) such that each Z(i) is an integer in the range {1,2,...,(n^2)-1,n^2}. Let W be an array with elements W(1), W(2),...,W(n) such that each W(i) is in the range {n,n+1,...,(n^3)-1,n^3}.
Then consider the following fragment of code:
Analyse the complexity of this code for the best and worst case, counting 1 unit for each basic operation, and expressing the total count as function of n.
Now I think I the best case would be when N = 1. I.e W and Z have 1 as one element (both of value 1). Thus,
k := 0 num execs = 1
for i := 1 to n do number execs = n+1
for j := Z(i)*W(i) to n*n do number of execs = 2
k := k +1 number of execs = 1
O = 1 + (n+1) + 2 + 1
= O(n)
However in the case of the worst case I am currently feeling retarded
I think the worst case would be when Z(i ) = 1, W(i ) = n, so 1*n.
Now I can tell by looking at it that the code should be O(n^2) but im not sure how to come up with this in the worst case. Can anyone help?

Let Z be an array with elements Z(1), Z(2),...,Z(n) such that each Z(i) is an integer in the range {1,2,...,(n^2)-1,n^2}. Let W be an array with elements W(1), W(2),...,W(n) such that each W(i) is in the range {n,n+1,...,(n^3)-1,n^3}.
Then consider the following fragment of code:
Code:
k := 0
for i := 1 to n do
for j := Z(i)*W(i) to n*n do
k := k+1
Analyse the complexity of this code for the best and worst case, counting 1 unit for each basic operation, and expressing the total count as function of n.
Now I think I the best case would be when N = 1. I.e W and Z have 1 as one element (both of value 1). Thus,
k := 0 num execs = 1
for i := 1 to n do number execs = n+1
for j := Z(i)*W(i) to n*n do number of execs = 2
k := k +1 number of execs = 1
O = 1 + (n+1) + 2 + 1
= O(n)
However in the case of the worst case I am currently feeling retarded

I think the worst case would be when Z(i ) = 1, W(i ) = n, so 1*n.
Now I can tell by looking at it that the code should be O(n^2) but im not sure how to come up with this in the worst case. Can anyone help?
Last edited: