Data Structures & AlgorithmsVery hardICPC regional · subset enumeration

Problem: How many subsets of {1, 2, 3, 4} have a prime sum (the empty set has sum 0 and is not prime)? Run the code.

Problem: How many subsets of {1, 2, 3, 4} have a prime sum (the empty set has sum 0 and is not prime)? Run the code.
from itertools import combinations
a = [1, 2, 3, 4]
def prime(n):
    return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1))
print(sum(1 for r in range(len(a) + 1) for c in combinations(a, r) if prime(sum(c))))
What is printed?
  1. A. 7
  2. B. 9
  3. C. 13
  4. D. 4

Correct answer: A. 7

The prime-sum subsets are {2}, {3}, {1,2}, {1,4}, {2,3}, {3,4} and {1,2,4}: 7. Dropping the n > 1 test makes the sums 0 and 1 'prime' (9), using range(2, int(√n)) without + 1 lets 4, 6, 8 and 9 through (13), and counting distinct prime sums 2, 3, 5, 7 gives 4.

More Coding Interview Problems questions

Exams that ask this topic