Complexity of two algorithms -


i studying algorithms complexity, , have question difference between following 2 algorithms:

algorithm #1:

sum = 0 = 1  while (i < n) {     j = 1 {        sum = sum + 1    }     = i*2; }  return sum 

algorithm #2:

sum = 0 = 1  while (i < n) {     j = 1 n {        sum = sum + 1    }     = i*2; }  return sum 

the difference 'for' loop, difference between time complexity of these algorithms ? when have multiply or add complexity of nested loops?

let simplisity n power of 2 i.e. 2^k. obvious outer loop proceed k times , on each step inner loop proceed:

1 1 i.e. 2^0 1 2 i.e. 2^1 1 4 i.e. 2^2 ... 1        2^k 

so need find sum 2^0 + 2^1 + ... + 2^k

it knows 2^(k+1) - 1 = 2^k * 2 - 1 = 2*n + 1

so omitting constants o(n)

second 1 simple. outer loop log(n), inner n o(n*log(n)).


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -