Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analyzing General Algorithm Complexity

Assuming I have a program like this:

def fn(array,num):
   for i in range(0,len(array)):
     if(i==num):print i


   for i in range(o,len(array)):
     for j in range(0,i):
       if(i*j==num):print i,j

So the first loop runs in O(n) time . The second loop runs in O(n*n)time.

The overall time complexity would be O(n)+O(n^2) = O(n^2) time.(Is this right ??)

Also the space complexity would be O(n) as we have n blocks in memory to store n elements(Is this right ??) Is this the correct way to analyze the run time and space complexity?.I can analyze the time complexity of common sort algorithms and data strutures but Im having a bit of difficulty analyzing it just for a general program.Thanks!!

like image 788
ashwin shanker Avatar asked Dec 04 '25 17:12

ashwin shanker


1 Answers

This is going to be O(n^2) as n grows n^2 will dwarf the O(n) section so that part drops out. For example when n is 100. The first operation will take 100 units of time and the second will take 10,000 units. 99% of the time calculating will be spent on the second operation. As n increases the second operation will continue to dominate. I see no reason it wouldn't be O(n) space complexity.

like image 191
ford prefect Avatar answered Dec 09 '25 08:12

ford prefect



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!