Python Program - Find all Prime Numbers less than the given Number


Advertisements

A Prime number is a natural number greater than $$1$$ and divisible by $$1$$ and itself only, for example $$- 2, 3, 5, 7,$$ etc.

Objective: Write a python code to find all prime numbers less than a given number.

Example: Using function to find prime number

In the below example, a function called primenumber() is created which takes a number as argument and checks it for prime number by dividing it with all natural numbers starting from $$2$$ to $$\frac{N}{2}$$.

def primenumber(MyNum):
  n = 0
  i = 2
  for i in range(2,MyNum//2+1):
    if MyNum % i == 0:
      n = n + 1
      break
  if n == 0:
    print(MyNum, end=" ")

x = 50
print("Prime numbers less than", x, "are:")
for i in range(2, x+1):
  primenumber(i)

Output

Prime numbers less than 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

Example: Optimized Code

  • Instead of checking the divisibility of given number from $$2$$ to $$\frac{N}{2}$$, it is checked till $$\sqrt{N}$$. For a factor larger than $$\sqrt{N}$$, there must the a smaller factor which is already checked in the range of $$2$$ to $$\sqrt{N}$$.
  • Except from $$2$$ and $$3$$, every prime number can be represented into $$6k\pm1$$.

def primenumber(MyNum):
  n = 0
  i = 2
  if MyNum == 2 or MyNum == 3:
    print(MyNum, end=" ")
  elif MyNum % 6 == 1 or MyNum % 6 == 5:
    while i*i <= MyNum:
      if MyNum % i == 0:
        n = n + 1
        break
      i = i + 1 
    if n == 0:
      print(MyNum, end=" ")

x = 100
print("Prime numbers less than", x, "are:")
for i in range(2, x+1):
  primenumber(i)

Output

Prime numbers less than 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97




Advertisements