Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the complexity?

Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the complexity?
def count_div_checks(n):
    i = 1; steps = 0
    while i * i <= n:
        steps += 1; i += 1
    return steps
print(count_div_checks(10**6), count_div_checks(99))
What is printed?
  1. A. 1000 10
  2. B. 1000 9
  3. C. 1000000 99
  4. D. 20 7

Correct answer: B. 1000 9

The loop stops once i exceeds √n, so it runs ⌊√n⌋ times: 1000 for 10⁶ and 9 for 99 (10² = 100 > 99). Complexity O(√n) – any divisor above √n pairs with one below it, so checking further is unnecessary. 20 would be log₂ n, which this loop is not.

More Coding Interview Problems questions

Exams that ask this topic