- Related Questions & Answers
- Check if a number is Primorial Prime or not in Python
- Python program to check if a number is Prime or not
- How to check whether a number is prime or not using Python?
- Check if a number is Quartan Prime or not in C++
- Check if a number is Primorial Prime or not in C++
- C# Program to check if a number is prime or not
- C++ Program to Check Whether a Number is Prime or Not
- 8085 program to determine if the number is prime or not
- C Program to Check Whether a Number is Prime or not?
- PHP program to check if a number is prime or not
- Check if a number is a Pythagorean Prime or not in C++
- Bash program to check if the Number is a Prime or not
- Write a C# program to check if a number is prime or not
- Prime Arrangements in Python
- Check if list is sorted or not in Python

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

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.

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.

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

Running the above code gives us the following result −

23 is a prime number

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.

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

Running the above code gives us the following result −

true false

Advertisements