Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Prime Hunter

Hard · 75 XP

Print all prime numbers between 2 and 50 on one line separated by spaces.

Target output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Blank · autosaved
PYprime-sieve.py
Run your code to check it…
Guide

How to approach Prime Hunter

A prime has no divisors other than 1 and itself. To test a number n, try dividing it by every candidate from 2 upwards; the first clean division (n % i == 0) proves it is not prime, and you can stop.

You never need to try past the square root of n. If n = a × b and both a and b were bigger than √n, their product would be bigger than n. So any factor pair has one member at or below √n, and range(2, int(n ** 0.5) + 1) covers it. Gather the primes as strings and join them with spaces.

Worked through on this data

  1. 2 and 3 have no candidates to try at all (their square roots are below 2), so both are prime.
  2. 49 tries 2 through 7: 49 % 7 == 0, so it is not prime. 47 tries 2 through 6 and nothing divides it, so it is prime.
  3. The full list is 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47: fifteen primes.

Common mistakes

  • Dropping the + 1: range(2, int(25 ** 0.5)) is 2, 3, 4, never tries 5, and wrongly reports 25 and 49 as prime.
  • Starting the outer range at 1: 1 is not prime by definition.
  • Forgetting to reset the is_prime flag for each new number, so one composite number marks everything after it as composite.

Time and space

Trial division is about O(n √n) for every number up to n. The Sieve of Eratosthenes crosses out multiples instead and runs in O(n log log n), which is far faster for large limits.

Where this shows up

Primes underpin RSA encryption and hash table sizing. The square-root bound is a general lesson: stop searching once the rest of the search space cannot contain an answer.

Take it further

Implement the actual Sieve of Eratosthenes: a list of booleans for 0 to 50, where you cross out every multiple of each prime you find.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path