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)
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…