Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

algorithm - order of growth for loop worst case running time

I am having trouble with this. The inner loop depends on the outer loop and from trying out values of n, the loop runs 1+2+4...+sqrt(n) times. Any help would be greatly appreciated!

int sum = 0;
for (int k = 1; k*k <= n; k = k*2)
    for (int j = 0; j < k; j++)
        sum++;
question from:https://stackoverflow.com/questions/66059293/order-of-growth-for-loop-worst-case-running-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If K is the largest power of 2 with K*K <= n, then your sum is 1+2+4+8+...+K = 2K+1.

K is clearly less than or equal to sqrt(n), but it's also greater than sqrt(n)/4 (because if not, then 2K*2K would be less than or equal to n, contradicting the fact that K is the largest power of 2 with K*K <= n.

So sqrt(n)/4 < K <= sqrt(n), and your runtime (2K+1) is between sqrt(n)/2+1 and 2sqrt(n)+1, and thus the complexity is Θ(sqrt(n)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...