-1

I'm learning about data structures and have been reading up on upper bounds. Most of the stuff I understand but my professor gave us a problem in class to solve on our own for fun. I'm not sure how to find the $O$ notation as a function of $N$ for this one.

for (i=1; i<=N; i++)
   for (j=1; j<=N; j+=i)
       x=i+j;

Also, does j+=1 make things different?

fade2black
  • 9,905
  • 2
  • 26
  • 36

1 Answers1

0

You have one cycle in another cycle. In general that can be represented as

$$\sum_{i=1}^n\Big(f(n)+\sum_{j(i)} g(k)\Big)$$

Since former cycle contains nothing except another cycle, $f(n)\equiv0$.

So, you need to calculate $h_i(n)\equiv\sum_{j(i)} g(n)$ for every $i$. I have replaced $k$ with $n$ since it depends only on $n$. To do it try to understand how many iterations inner cycle will have.

If you are not successful, here is a hint:

$h_1(n)\equiv n,~h_2(n)\equiv n/2,~h_3(n)\equiv n/3...$

Once you will find an exact runtime, you want to convert it to big O. Googling that gave me an answer quick. Hope it helps.

Don't open following spoiler if you haven't understood what the function is

Converting to big O.

rus9384
  • 2,111
  • 12
  • 17