- Related Questions & Answers
- Two Sum Less Than K in Python
- Python - Check if all the values in a list are less than a given value
- Count ordered pairs with product less than N in C++
- Find the sum of all Truncatable primes below N in Python
- Alternate Primes till N in C++?
- C++ Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
- Find all factorial numbers less than or equal to n in C++
- Print all prime numbers less than or equal to N in C++
- How to generate all permutations of a list in Python?
- Find maximum product of digits among numbers less than or equal to N in C++
- Find frequency of each element in a limited range array in less than O(n) time in C++
- How to generate a sorted list in Python?
- Count Primes in Python
- Program to find number of unique four indices where they can generate sum less than target from four lists in python
- Print all Semi-Prime Numbers less than or equal to N in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

12

[2, 3, 5, 7, 11]

Advertisements