Math Fundamentals18 sections · 814 units
Open in Course

Isolating Variables in Loops

Finding loop bounds

Sometimes you need to solve for loop bounds algebraically. For example, you want a loop that runs while k2nk^2 \leq n.

Solve for kk: knk \leq \sqrt{n}. So the loop runs from k=1k = 1 to k=nk = \lfloor \sqrt{n} \rfloor. This gives O(n)O(\sqrt{n}) iterations.

Another example: a loop doubles kk each iteration until knk \geq n. Solve 2i=n2^i = n to get i=log2ni = \log_2 n, meaning O(logn)O(\log n) iterations.