Introduction:
Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. Determining whether a given number is prime or not is a common problem in mathematics and computer science. In this tutorial, we’ll learn how to write a Python program to check if a number is prime or not.
Understanding Prime Numbers:
Before diving into the implementation, let’s understand the concept of prime numbers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers.
Approach to Check Primality:
To determine whether a number n is prime or not, we can follow the following approach:
- Check if the number is less than 2. If it is, it cannot be prime.
- Iterate from 2 to the square root of
n(inclusive) and check ifnis divisible by any of these numbers. - If
nis divisible by any number in this range, it is not prime. Otherwise, it is prime.
Python Implementation:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Test the function
num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Explanation:
- We define a function
is_primethat takes an integernas input. - We first check if
nis less than 2. If it is, we returnFalsebecause prime numbers are greater than 1. - We then iterate through the numbers from 2 to the square root of
n(inclusive) using a for loop. - Inside the loop, we check if
nis divisible by the current number (i). If it is, we returnFalsebecausenis not prime. - If the loop completes without finding any divisors of
n, we returnTrue, indicating thatnis prime.
Conclusion:
In this tutorial, we learned how to write a Python program to check if a given number is prime or not. Understanding prime numbers and implementing primality testing algorithms is essential in various mathematical and computational tasks. Happy coding!