Time complexity and number of calls
Question:
I have trouble finding the time complexity of my program and the exact formula to compute the number of calls (represented by the length of the list). Here is my python program that I wrote:
from math import *
def calc(n):
i = n
li = []
while i>0:
j = 0
li.append(1)
while j<n:
li.append(1)
k = j
while k<n:
li.append(1)
k+=1
j+=1
i = floor(i/2)
return len(li)
for i in range(1, 16):
print(calc(i))
Answers:
For computing time complexity of this program we come from most inner loop.
k=j
while k<n:
li.append(1)
k+=1
Here k iterate one by one forward move start from j to n. That means it run (n-k) time. Now back to the outer loop of this inner loop.
j=0
while j<n:
li.append(1)
k = j
//(n-j)
j+=1
Here j also iterate one by one from 0 to n. Total n times. And for every j inner loop iterate n-j.
while j=0 than k=0,1,2,3,….(n-1) Total n times
while j=1 than k=1,2,3,….(n-1) Total n-1 times
while j=2 than k=2,3,4,….(n-1) Total n-2 times
….
….
while j=n-1 than k=(n-1) Total 1 times
Total complexity = 1+2+3+……(n-2)+(n-1)+n
=(n*(n+1))/2;
Now the outer loop for i :
i=n
while i>0:
(n*(n+1))/2;
i = floor(i/2)
Here i start from n and every time divided by 2. We know if it iterate dividing by x than it’s complexity will log(base x)(n). Hence, for i the complexity will approximately log(base 2)(n).
Hence the Total time complexity is approximately log(n)(n(n+1))/2;
it also can be represented as O(n^2*log(n)).
I have trouble finding the time complexity of my program and the exact formula to compute the number of calls (represented by the length of the list). Here is my python program that I wrote:
from math import *
def calc(n):
i = n
li = []
while i>0:
j = 0
li.append(1)
while j<n:
li.append(1)
k = j
while k<n:
li.append(1)
k+=1
j+=1
i = floor(i/2)
return len(li)
for i in range(1, 16):
print(calc(i))
For computing time complexity of this program we come from most inner loop.
k=j
while k<n:
li.append(1)
k+=1
Here k iterate one by one forward move start from j to n. That means it run (n-k) time. Now back to the outer loop of this inner loop.
j=0
while j<n:
li.append(1)
k = j
//(n-j)
j+=1
Here j also iterate one by one from 0 to n. Total n times. And for every j inner loop iterate n-j.
while j=0 than k=0,1,2,3,….(n-1) Total n times
while j=1 than k=1,2,3,….(n-1) Total n-1 times
while j=2 than k=2,3,4,….(n-1) Total n-2 times
….
….
while j=n-1 than k=(n-1) Total 1 times
Total complexity = 1+2+3+……(n-2)+(n-1)+n
=(n*(n+1))/2;
Now the outer loop for i :
i=n
while i>0:
(n*(n+1))/2;
i = floor(i/2)
Here i start from n and every time divided by 2. We know if it iterate dividing by x than it’s complexity will log(base x)(n). Hence, for i the complexity will approximately log(base 2)(n).
Hence the Total time complexity is approximately log(n)(n(n+1))/2;
it also can be represented as O(n^2*log(n)).