Big-O Analysis for the Loop Algorithm

I am having trouble analyzing the following loop algorithm:

for (int i = 1; i < n; i = i * C)
    for (int j = 0; j < i; j++)
        Sum[i] += j * Sum[i];

I know the first line has O (logn) complexity (before C> 1), but what puzzled me was the second line. I suppose I understand the basics of what happens to him:

For instance,

if n = 20, the inner loop will make 1 + 2 + 4 + 8 + 16 "work."

But I don’t know how to write it out. I am pretty sure that the general work done in general in loops is O (n), and that the first line is O (logn), but how do I more specifically indicate what the middle line does?

+4
source share
2 answers

i will have form values:

C^0, C^1, C^2, ...., C^ log_c(n)

Consequently, the inner loop will run C^0 + C^1 + C^2 + ... + C^log_c(n)once. This is a geometric series that sums up to:

enter image description here

, r C, n log_c(n) :

(1-C^log_c(n)) / (1-C) = (1-n)/(1-C), C > 1 n. , O(n) .

( Wikipedia)

+3

sum_{k=a}^b f(i) f(a) + f(a + 1) + ... + f(b), a^b, a, b - .

p , C^p < n <= C^{p+1} , . i 1, C, C^2, C^3, ..., C^p, C^k k=0, ..., p. , k i = C^k . , T ( ):

T = C^0 + C^1 + ... + C^p = sum_{k=0}^p C^k = (C^{p + 1} - 1) / (C - 1)

. , p, :

p < log_C(n) <= p+1

, , p :

log_C(n) - 1 <= p < log_C(n)

x -> (C^{x + 1} - 1) / (C - 1):

(n - 1) / (c - 1) <= (C^{p + 1} - 1) / (C - 1) = T < (Cn - 1) / (c - 1)

T O(n) (, , Theta(n)) . , O(n) (, , Theta(n), , ).

0

Source: https://habr.com/ru/post/1692778/


All Articles