Generate a list of Primes less than n in Python

PythonServer Side ProgrammingProgramming

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
  • return primes

Let us see the following implementation to get better understanding −

Example

 Live Demo

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]
raja
Published on 23-Sep-2020 10:22:42
Advertisements