Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice
Problem: How many integers n in [1, 100] reach 1 under the Collatz map within 10 steps? Run the code.
Problem: How many integers n in [1, 100] reach 1 under the Collatz map within 10 steps? Run the code.
def steps(n):
c = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
c += 1
return c
print(sum(1 for n in range(1, 101) if steps(n) <= 10))What is printed?- A. 20
- B. 2
- C. 25
- D. 22
Correct answer: D. 22
Exactly 22 starting values in 1..100 need at most 10 steps (n = 1 needs 0). Using a strict < 10 test gives 20, counting only those needing exactly 10 steps gives 2, and loosening the bound to 11 steps gives 25.
More Coding Interview Problems questions
- Problem: How many ordered pairs (a, b) with 1 <= a, b <= 30 have a^2 + b^2 a perfect square? Run the code. python print(sum(1 for a in…
- Problem: How many distinct strings can be formed by rearranging the letters of 'aabbc'? Run the code. python from itertools import…
- Problem: A 3-person committee is chosen from 6 people. How many committees include at least one of two specific people A or B? Run the…
- Problem: How many non-negative integer solutions (x, y, z) of x + y + z = 10 satisfy x <= 4? Run the code. python print(sum(1 for x in…
- Problem: How many pairs (x, y) with x <= y and x + y = 12 lie in 1..11? Run the code. python print(sum(1 for x in range(1, 12) for y in…
- Problem: How many inversions does the array [4, 3, 2, 1, 0] have? Run the code. python a = [4, 3, 2, 1, 0] print(sum(1 for i in…