v9.1.1
Menu

Prime Finder

mediumFREEControl FlowPython AlgorithmsPython Foundations

Problem Statement

Find all prime numbers up to a given limit.

Background

A prime number is only divisible by 1 and itself. The Sieve of Eratosthenes is an efficient algorithm:

  1. Create a list of numbers from 2 to n
  2. Start with the first prime (2)
  3. Remove all multiples of that prime
  4. Move to the next unmarked number
  5. Repeat until done

Your Task

Write a function find_primes(n) that returns all prime numbers up to n.

Output Format

Return a list of prime numbers in ascending order.

Example

Input
n = 20
Output
[2, 3, 5, 7, 11, 13, 17, 19]
Reasoning
  • Input: n = 20 is an inclusive upper limit, so the candidates are the 19 whole numbers 2,3,…,202, 3, \dots, 20 (1 is not prime by definition).
  • A number is composite exactly when it has a prime factor smaller than itself. If m=a⋅bm = a \cdot b with a≤ba \le b, then a2≤m≤20a^2 \le m \le 20, so a≤20≈4.47a \le \sqrt{20} \approx 4.47. Every composite up to 20 is therefore divisible by 2 or 3.
  • Multiples of 2 (other than 2 itself): 4,6,8,10,12,14,16,18,204, 6, 8, 10, 12, 14, 16, 18, 20, which is 9 composites.
  • Multiples of 3 not already listed: 9=329 = 3^2 and 15=3⋅515 = 3 \cdot 5, which is 2 more. Note that 6,12,186, 12, 18 were already counted.
  • That leaves 19−11=819 - 11 = 8 survivors: [2, 3, 5, 7, 11, 13, 17, 19].
  • Output: a list of integers in ascending order. Notice that the limit is inclusive: with n = 19, 19 would still appear, and with n = 2 the answer is [2].

Constraints

  • n >= 2
  • Use an efficient approach for larger n

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.