Algorithms and Data Structures · Junior · Question 65 of 75

What is the complexity of this loop?

for (let i = 1; i < n; i *= 2) {
  console.log(i);
}

Explanation

i doubles each step: 1, 2, 4, 8... It reaches n after about log₂ n iterations. Loops where the variable is multiplied or divided by a constant are logarithmic.

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 65

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz