![]() |
VOOZH | about |
Given a number n, find all prime numbers less than or equal to n.
Examples:
Input: n = 10
Output: [2, 3, 5, 7]
Explanation: The prime numbers up to 10 obtained by Sieve of Eratosthenes are [2, 3, 5, 7].Input: n = 35
Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
Explanation: The prime numbers up to 35 obtained by Sieve of Eratosthenes are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31].
Table of Content
The Naive Approach for finding all prime numbers from
1toninvolves checking each number individually to determine whether it is prime.
Step By Step Implementations:
i from 2 to n.i, check if it is divisible by any number from 2 to i - 1.i is not prime.i is prime.The Sieve of Eratosthenes efficiently finds all primes up to
nby repeatedly marking multiples of each prime as non-prime, starting from 2. This avoids redundant checks and quickly filters out all composite numbers.
Step By Step Implementations:
rime[0..n] and set all entries to true, except for 0 and 1 (which are not primes).p from 2 up to √n:p is marked as prime(true):p as not prime(false), starting from p * p (since smaller multiples have already been marked by smaller primes).true entries in prime represent prime numbers.2 3 5 7 11 13 17 19 23 29 31
Time Complexity: O(n*log(log(n))). For each prime number, we mark its multiples, which takes around n/p steps. The total time is proportional to n*(1/2 + 1/3 + 1/5 + ....).
This sum over primes grows slowly and is approximately O(n*log(log(n))) making the algorithm very efficient.
Auxiliary Space: O(n)
Related articles