61. What is the time complexity of a loop where `i` starts at 1 and is multiplied by 2 each iteration until it exceeds n? What about a loop that runs while `i * i <= n`?
EasyAlgorithm analysis
Technical
Show model answer
After k iterations i = 2^k, so the loop stops once 2^k > n, i.e. after about log_2 n + 1 iterations: O(log n). The same holds for any constant multiplier or divisor greater than 1 (only the base of the log changes, which is a constant factor).
A loop that increments i by 1 while i*i <= n stops when i passes the square root of n, so it runs about sqrt(n) times: O(sqrt n). This is the classic primality-check bound.