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?- A. 1000 10
- B. 1000 9
- C. 1000000 99
- 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
- Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce? python…
- Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024? python def cnt(n): c = 0 for i in…
- Problem: Find the bug: a backtracking routine collects all subsets of [1, 2]. python def subsets(a): res, path = [], [] def bt(i): if i ==…
- Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … +…
- Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas. python fs = [lambda x: x i for i in range(1, 4)] gs…
- Problem: Find the bug: even values are removed from a list while iterating over that same list. python nums = [2, 4, 4, 6, 5, 8] for x in…