- Related Questions & Answers
- Super Prime in c programming
- 10 Interesting Python Cool Tricks
- howdoi in Python
- How to print without newline in Python?
- How to download Google Images using Python
- How to clear screen in python?
- get() method for dictionaries in Python
- Generating random number list in Python
- gcd() function Python
- frozenset() in Python
- floor() and ceil() function Python
- float() in Python
- Finding Mean, Median, Mode in Python without Libraries
- Find the k most frequent words from data set in Python
- Find size of a list 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