Data Structures & AlgorithmsHardTCS NQT · counting
Problem: How many integers in [1, 1000] are perfect squares or perfect cubes?
Problem: How many integers in [1, 1000] are perfect squares or perfect cubes?
print(sum(1 for x in range(1, 1001) if any(k * k == x for k in range(1, 32)) or any(k ** 3 == x for k in range(1, 11))))What is printed?
- A. 41
- B. 37
- C. 31
- D. 38
Correct answer: D. 38
There are 31 squares (1 to 31²), 10 cubes (1 to 10³), and 3 numbers that are both, the sixth powers 1, 64 and 729, so 31 + 10 − 3 = 38. Forgetting the overlap gives 41, stopping k at 30 misses 961 (37), and counting only squares gives 31.
More Coding Interview Problems questions
- Problem: Greedy graph colouring assigns colours in vertex order 0, 1, 2, 3, 4, 5, giving each vertex the smallest colour (starting at 0)…
- Problem: In the undirected graph with edges 0-1, 0-2, 1-2, 1-3, 2-3, 3-4, how many simple paths (no repeated vertex) go from vertex 0 to…
- Problem: An undirected forest (a graph with no cycles) has 9 vertices and 6 edges. How many connected components does it have?
- Problem: A rooted tree (root 1) has parent pointers: 2→1, 3→1, 4→2, 5→2, 6→4, 7→6, 8→3, 9→8. How many nodes lie on the path between node 7…
- Problem: For the complete binary tree with 10 nodes stored in heap order (node i has children 2i and 2i+1, root is node 1), what is the…
- Problem: Using the parent array par[i] for nodes 0–9 with par = [−1, 0, 0, 1, 1, 3, 3, 5, 6, 8], what is the 3rd ancestor of node 9 (the…