How to calculate the time complexity for (int i = n - 1; i! = 0; i / = 2)?

for (int i = n - 1; i != 0; i /= 2) ++k;

I cannot figure out how to calculate the time complexity for the above. I can not understand his behavior when n is negative. can anyone help me get there. I tried when n is positive.

Statement            Code      Time 
1a                  i=n-1       1 
1b                  i != 0    log2n+1
1c                  i = i/2   log2n
2                    ++k      log 2n
Total running time       3 log 2n+2

I got these values ​​when I parsed the code for n to be positive. but I could not get when n is negative

+4
source share
1 answer

O (log (n)). , abs(n - 1) - 2, i /= 2 , i ( ) , abs(i / 2), - .

n - 1 2, n - 1 == 2**a a, a + 1 ( i, 1 = 2**0, 2 = 2**1, 4 = 2**2,..., n - 1 = 2**a). lg (n - 1) + 1 .

, , , , , . , () O (log (n)), , " n" /log (n), n , . , , ? log (n) , . (2, 10 e, ) lg (n - 1) lg ( n - 1 + (-) m) + (-) p m p.

+4

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


All Articles