Prime Hunter
Hard · 75 XPPrint all prime numbers between 2 and 50 on one line separated by spaces.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
A number n is prime if no i in range(2, int(n**0.5)+1) divides it.
primes = []
for n in range(2, 51):
is_prime = True
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
is_prime = False
break
if is_prime:
primes.append(str(n))
print(" ".join(primes))
Run your code to check it…
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
- 2 and 3 have no candidates to try at all (their square roots are below 2), so both are prime.
- 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.
- 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_primeflag 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.