Data Structures & AlgorithmsModerateTCS NQT · number theory

Problem: What is the sum of all primes up to 50? Run the code.

Problem: What is the sum of all primes up to 50? Run the code.
print(sum(p for p in range(2, 51) if all(p % d for d in range(2, int(p ** 0.5) + 1))))
What is printed?
  1. A. 275
  2. B. 304
  3. C. 330
  4. D. 328

Correct answer: D. 328

The primes up to 50 are 2, 3, 5, ..., 47, and their sum is 328. Including 1 or excluding 2 gives the nearby wrong totals.

More Coding Interview Problems questions

Exams that ask this topic