- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate a list of Primes less than n in Python
Suppose we have a number n, we have to generate a list of all prime numbers smaller than or equal to n in ascending order. We have to keep in mind that 1 is not a prime number.
So, if the input is like 12, then the output will be [2, 3, 5, 7, 11].
To solve this, we will follow these steps −
- sieve := a list of size n+1 and fill with True
- primes := a new list, initially blank
- for i in range 2 to n, do
- if sieve[i] is True, then
- insert i at the end of primes
- for j in range i to n, update in each step by i, do
- sieve[j] := False
- if sieve[i] is True, then
- return primes
Let us see the following implementation to get better understanding −
Example
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 ob = Solution() print(ob.solve(12))
Input
12
Output
[2, 3, 5, 7, 11]
Advertisements