问题
i <-- 0
while(i < n)
someWork(...)
i <-- i^2
done
Can someone confirm that the worst case time complexity (Big-O) of this loop is O(log n) if:
someWork(...)is anO(1)algorithmsomeWork(...)is anO(n)algorithm
Also, what is the worst case time complexity (Big-O) if someWork(...) does exactly i operations? someWork(...) does more work as i increases. Your answer should be something like sigma(f(i)).
Thank you very much for any help.
回答1:
First: if (as mentioned) 0 <= i <= 1 holds, the algorithm will never terminate.
So: Let i > 1.
In every round of the loop the exponent of i will be doubled. So in the k-th round the number will be i^(2^k). The loop keeps going as long as i^(2^k) < n holds, which is equivalent to k < log log n. Exactly it is log_2 log_i n, but due to all logarthms are equal exept for a constant factor, I just write log log n. Notice: if i is not constant, 1/log log i has to be multiplied to the complexity.
So the complexity of the algorithm is
O(log log n), ifsomeWork()is inO(1)O(n log log n), ifsomeWork()is inO(n)
If someWork() does O(i^(2^k)) operations in round k you get a total complexity of
O( i + i^2 + i^(2^2) + i^(2^3) + ... + i^(2^(log log n)) )
This simplifys to O(i * i^(2^(log log n)) ) = O(i * n) or O(n) if i is constant.
To see the simplification take a look at the following:
The number i + i^2 + i^4 + i^8 can be written in i-ary as
100 010 110. So you can see that
i + i^(2^1) + i^(2^2) + ... + i^(2^k) < i * i^(2^k)
holds, since it is equal to 100 010 110 < 1 000 000 000.
Edit:
I'm not sure what you mean by sigma notation but maybe it is this:
来源:https://stackoverflow.com/questions/24581182/asymptotic-complexity-for-an-algorithm