Prime or not in Python


Prime numbers play a central role in many e it applications like cryptography. So it is a necessity to check for prime numbers using Python programs in various applications. A prime number is a number which doesn't have any factors other than one and itself. Below will see programs that can find out if a given number is prime or not.

Approach

We take the following approach to decide whether a number is prime or not.

  • Check at the beginning is positive or not. As only positive numbers can be prime numbers.

  • We divide the number with all the numbers in the range of 2 to one number less than given number.

  • If the remainder becomes zero for any number in this range then it is not a prime number.

Example

 Live Demo

x = 23
if x > 1:
   for n in range(2, x):
      if (x % n) == 0:
         print(x, "is not prime")
         print(n, "times", x // n, "is", x)
         break
   else:
      print(x, "is a prime number")
   else:
      print(x, "is not prime number")

Output

Running the above code gives us the following result −

23 is a prime number

Checking for the form 6i+1

All prime numbers which are greater than 6 can be represented in the form of 6i+1. Here I starts from 1 and goes on as integer. In the below example we will check if the number can be presented in the form of 6i+1 by dividing its 6 and checking for a reminder as one. Accordingly, will decide if the number is prime or not. Also we need to check for a i value which is equal to square root of the given number.

Example

 Live Demo

def CheckPrime(n):
   # Check for cases of 2 and 3
   if (n <= 1):
      return False
   if (n <= 3):
      return True
   # skip checking middle five numbers in the loop
   if (n % 2 == 0 or n % 3 == 0):
      return False
   i = 5
   while (i * i <= n):
      if (n % i == 0 or n % (i + 2) == 0):
         return False
      i = i + 6
   return True
# Check for inputs
if (CheckPrime(31)):
   print(" true")
else:
   print(" false")
if (CheckPrime(25)):
   print(" true")
else:
   print(" false")

Output

Running the above code gives us the following result −

true
false
raja
Published on 04-Feb-2020 06:50:29
Advertisements