问题
I have these 2 questions - I believe one was posted earlier - but was unanswered. I think I have answered 2nd one correctly ...
Any suggestions ?
work out f(n), the exact number of unit-time operations each procedure requires as a function of the input size n
(i) for i<-1 to n do
for j<-1 to 2n-i do
//a unit cost operation
------------------------------ (i) this is i the one i need some help on.
(ii) for i <-1 to n do
for j <- 2 to (n+i) do
// a unit cost operation
for i: 1 to n do:
for j: 2 to n + i do:
unit
now, let's say n=1
i=1; j: 2 to 2 = 1 times
total: 1 units
n=2
i=1; j: 2 to 3 = 2 times
i=2; j: 2 to 4 = 3 times
total: 2 + 3 = 5 units
n=3
i=1; j: 2 to 4 = 4 times
i=2; j: 2 to 5 = 5 times
i=3; j: 2 to 6 = 6 times
total: 4 + 5 + 6 = 10 units
Pattern being f(n) = n^2 +1 , is that right?
回答1:
For the case you mentioned(case (i)) you can use Arithmetic Progressions
In this case as first term=2*n-1 and the last term is n, so sum of all the terms is
S=n/2*(n+2*n-1)=O(n^2)
For the Case II, first term=(n+1-1)=n and last term=(n+n-1)=(2*n-1), so Sum, S is equal to,
S=n/2(first term+last term)=n/2*(n+2*n-1)=O(n^2)
You must have observed that S for both (i) & (ii) are same.
来源:https://stackoverflow.com/questions/23374126/work-out-fn-the-exact-number-of-unit-time-operations-each-procedure-requires