0

I am trying to prepare for a test comping up on run-time analysis. I have been hit with a for loop that is throwing me a bit. I am hoping someone can help me.

the loop is

for(j=1; j< n; j=j*2)

J is increasing at an increasing rate so it will be less than n/2 however I am having trouble concluding what exactly it will be.

Raphael
  • 73,212
  • 30
  • 182
  • 400
Peter3
  • 103
  • 3

1 Answers1

1

In your loop, $j$ will take the values $1, 2, 4, 8, \dotsc, 2^k$ where $2^k<n$. You need to know how many times this will iterate. In other words, what will be the largest $k$ for which we have $2^k < n$? Take the log to the base 2 of each side of the inequality and you're asking what the largest $k$ will be for which $k<\log_2n$. What this means is that you're right in your comment: the loop will iterate no more than $\log_2n$ times.

Rick Decker
  • 15,016
  • 5
  • 43
  • 54