In this article we will look at how to check if a number is a prime number using python. This is a fairly common basic programming exercise in many languages.
First lets look at a basic definition of what a prime number is
Definition
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number.
For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. However, 4 is composite because it is a product (2 × 2) in which both numbers are smaller than 4
The first 25 prime numbers (all the prime numbers less than 100) are as follows
- 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
No even number greater than 2 is prime because any such a number can be expressed as the product . Therefore, every prime number other than 2 is an odd number.
Similarly, when written in the usual decimal system, all prime numbers larger than 5 end in 1, 3, 7, or 9.
The numbers that end with other digits are all composite: decimal numbers that end in 0, 2, 4, 6, or 8 are even, and decimal numbers that end in 0 or 5 are divisible by 5
Now lets delve into a python program
Python Example
Save the following as isaprime.py or similar
# A function for checking if anumber is a prime number def CheckPrime(num): # Checking that given number is greater than 1 if num > 1: # Iterating over the given number with for loop for j in range(2, int(num/2) + 1): # If the given number is divisible or not if (num % j) == 0: print(num, "is not a prime number") break # it is a prime number else: print(num, "is a prime number") # If the number is 1 else: print(num, "is not a prime number") # Get input from the user num = int(input("Enter an input number:")) # Print the result CheckPrime(num)
Now run he program, I used thonny. You can use some of the 25 prime numbers as test data.
Here are a few test runs
Python 3.7.9 (bundled)
>>> %Run isaprime.py
Enter an input number:1
1 is not a prime number
>>> %Run isaprime.py
Enter an input number:2
2 is a prime number
>>> %Run isaprime.py
Enter an input number:58
58 is not a prime number
>>> %Run isaprime.py
Enter an input number:59
59 is a prime number
>>>
Link
This is on GitHub if you would rather look at the code there and download
https://github.com/programmershelp/maxpython/blob/main/code%20example/isaprime.py