Different Methods to find Prime Number in Python Program


In this tutorial, we are going to explore different methods to find whether a given number is valid or not. Let's start without further due.

Method-1

It's a general method to find prime numbers.

  • If the number is less than or equal to one, return False.

  • If the number is divisible by any number, then the function will return False.

  • After the loop, return True.

Example

 Live Demo

# checking for prime
def is_prime(n):
   if n <= 1:
      return False
   else:
      for i in range(2, n):
         # checking for factor
         if n % i == 0:
            # return False
            return False
      # returning True
   return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")

Output

If you run the above code, then you will get the following result.

Is 2 prime: True
Is 4 prime: False
Is 7 prime: True

Method-2

In this method, we are reducing the number of iterations by cutting them to the square root of n.Let's see the code.

Example

 Live Demo

import math
# checking for prime
def is_prime(n):
   if n <= 1:
      return False
   else:
      # iterating loop till square root of n
      for i in range(2, int(math.sqrt(n)) + 1):
         # checking for factor
         if n % i == 0:
            # return False
            return False
      # returning True
      return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")

Output

If you run the above code, then you will get the following result.

Is 2 prime: True
Is 4 prime: False
Is 7 prime: True

Method-3

In the previous method, we have checked for the even numbers. We all know that even numbers can't be prime except two. So, in this method, we will remove all evens to reduce the time.

Example

 Live Demo

import math
# checking for prime
def is_prime(n):
   # checking for less than 1
   if n <= 1:
      return False
   # checking for 2
   elif n == 2:
      return True
   elif n > 2 and n % 2 == 0:
      return False
   else:
      # iterating loop till square root of n
      for i in range(3, int(math.sqrt(n)) + 1, 2):
         # checking for factor
         if n % i == 0:
            # return False
            return False
      # returning True
      return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")

Output

If you run the above code, then you will get the following result.

Is 2 prime: True
Is 4 prime: False
Is 7 prime: True

Conclusion

If you have doubts in the tutorial, mention them in the comment section.

Updated on: 24-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements