Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write an endless generator primes() that gives 2, 3, 5, 7, 11, ... A number is prime if no smaller number from 2 up to its square root divides it. Show the first ten primes.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Try each number from 2 upward. A number n is prime when no d from 2 to the whole part of the square root of n divides it. Yield the primes.
Check. The first ten primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29. The test d * d <= n is the same as d up to the square root of n, and it avoids a decimal number.
Answer: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].
Log in to join the discussion.
Loading…