Iterators and generators · 11 / 15 Exercise Medium

Infinite primes

Objective

Create a Python program with an infinite generator of prime numbers and take only the first ones with itertools.islice.

Instructions

  • Define def primes(), which starts at n = 2 and, in a while True, yields n if it is not divisible by any number between 2 and its square root (all(n % d != 0 for d in range(2, int(n ** 0.5) + 1))), and moves on to the next number.
  • Read an integer n (at least 1).
  • Get the first n primes with islice(primes(), n) and show them on one line, separated by spaces.
Input
8
Output
2 3 5 7 11 13 17 19

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise