algorithm - Big-O complexity of a piece of code -


i have question in algorithm design complexity. in question piece of code given , should calculate code's complexity. pseudo-code is:

for(i=1;i<=n;i++){     j=i     do{         k=j;         j = j / 2;     }while(k even); } 

i tried algorithm numbers. , have gotten different results. example if n = 6 algorithm output below

i = 1 -> executes 1 time = 2 -> executes 2 times = 3 -> executes 1 time = 4 -> executes 3 times = 5 -> executes 1 time = 6 -> executes 2 times 

it doesn't have regular theme, how should calculate this?

the upper bound given other answers high. algorithm has o(n) runtime, tighter upper bound o(n*logn).

proof: let's count how many total iterations inner loop perform.

the outer loop runs n times. inner loop runs @ least once each of those.

  • for i, inner loop runs @ least twice. happens n/2 times.
  • for i divisible 4, inner loop runs @ least 3 times. happens n/4 times.
  • for i divisible 8, inner loop runs @ least 4 times. happens n/8 times.
  • ...

so total amount of times inner loop runs is:

n + n/2 + n/4 + n/8 + n/16 + ... <= 2n 

the total amount of inner loop iterations between n , 2n, i.e. it's Θ(n).


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -