![]() |
VOOZH | about |
Given a number n, the task is to find and print all the prime numbers smaller than or equal to n. A prime number is a number greater than 1 that is divisible only by 1 and itself. For example:
Input: n = 20
Output: 2, 3, 5, 7, 11, 13, 17, 19
Let’s explore different methods to find all prime numbers up to a given number in Python.
In this method, we start by assuming all numbers are prime and progressively mark the multiples of each prime as non-prime. This efficiently eliminates composites using a boolean list.
2 3 5 7 11 13 17 19 23 29
Explanation:
Here, we use NumPy arrays to speed up marking non-prime numbers with vectorized operations. It’s faster for large n due to optimized array handling.
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Explanation:
In this concise method, list comprehension checks each number’s divisibility by all numbers up to its square root and keeps only primes. It’s compact but slower than the sieve methods.
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Explanation:
This method checks divisibility for each number up to n. Though simple and easy to understand, it’s computationally expensive for large numbers.
2 3 5 7 11 13 17 19 23 29
Explanation:
Please refer complete article on Sieve of Eratosthenes for more details!