0

I have to find the time complexity of the below code. But got confused as the j is increasing acccording to the value of i.

Else I thought it would be $O(n^2)$.

#include <iostream> 
using namespace std; 
for(int i=0;i<n;i++) 
    { 
      for(int j=0;j<n;j+=i) 
      { 
        //Some O(1) Code 
      } 
    }
4
  • This sounds like a bit of a trick question to me, since if n is anything above 0, you would have a non-terminating program. Commented Nov 29, 2020 at 4:03
  • @costaparas n is just a variable which a user can give any value Commented Nov 29, 2020 at 4:04
  • For n>0 the execution time will be infinite, as in the very first iteration of the outer loop i=0, so the increment of the inner loop will be j=j+0, causing j ro remain 0 forever. Commented Nov 29, 2020 at 7:32
  • For n <0, instead, the outer loop condition will be false since the very first iteration, so //Some O(1) Code will never be executed. Commented Nov 29, 2020 at 7:34

2 Answers 2

1

As others have stated, assuming $n > 0$ then on the first iteration of the outer loop the inner loop will have increment 0 and never terminate.

If instead you meant for the inner loop to increment by i+1, then the total number of iterations is given as:

Link to latex: I don't have enough reputation to embed images.

Where H_n is the n-th harmonic number.

So complexity is O(n log n).

Sign up to request clarification or add additional context in comments.

Comments

0

The time complexity is not defined for this function since it doesn't terminate on all inputs. In fact, it only terminates for n <= 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.