Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generate a list of Primes less than n in Python
Finding all prime numbers less than or equal to a given number n is a classic problem in computer science. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We'll use the Sieve of Eratosthenes algorithm, which is one of the most efficient methods for finding all primes up to a given limit.
So, if the input is like 12, then the output will be [2, 3, 5, 7, 11].
Algorithm Steps
To solve this, we will follow these steps ?
- Create a boolean array
sieveof size n+1 and initialize all values to True - Create an empty list
primesto store the result - For each number i from 2 to n:
- If
sieve[i]is True, then i is prime:- Add i to the primes list
- Mark all multiples of i as False in the sieve
- If
- Return the primes list
Implementation
class Solution:
def solve(self, n):
sieve = [True] * (n + 1)
primes = []
for i in range(2, n + 1):
if sieve[i]:
primes.append(i)
for j in range(i, n + 1, i):
sieve[j] = False
return primes
# Test the solution
ob = Solution()
print(ob.solve(12))
[2, 3, 5, 7, 11]
Alternative Approach: Simple Function
Here's a simpler implementation without using a class ?
def generate_primes(n):
if n < 2:
return []
sieve = [True] * (n + 1)
primes = []
for i in range(2, n + 1):
if sieve[i]:
primes.append(i)
# Mark all multiples of i as composite
for j in range(i * i, n + 1, i):
sieve[j] = False
return primes
# Test with different values
print("Primes ? 12:", generate_primes(12))
print("Primes ? 20:", generate_primes(20))
print("Primes ? 30:", generate_primes(30))
Primes ? 12: [2, 3, 5, 7, 11] Primes ? 20: [2, 3, 5, 7, 11, 13, 17, 19] Primes ? 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
How It Works
The Sieve of Eratosthenes works by iteratively marking the multiples of each prime number as composite (non-prime). Starting with 2, we mark all its multiples as False. Then we move to the next unmarked number (which must be prime) and repeat the process.
Time and Space Complexity
- Time Complexity: O(n log log n) - very efficient for finding all primes up to n
- Space Complexity: O(n) - for the boolean sieve array
Conclusion
The Sieve of Eratosthenes is the most efficient algorithm for generating all prime numbers up to a given limit. It systematically eliminates composite numbers, leaving only primes in the final result.
