A prime number is a number that is only divisible by 1 and itself.
In this tutorial, we will write a Python program to check whether a given number is prime or not.
To check whether a number is prime or not, we need to iterate through all the numbers from 2 to n-1, where n is the given number.
If we find any number between 2 and n-1 that divides n evenly, then the number is not prime.
If no number between 2 and n-1 divides n evenly, then the number is prime.
Let’s implement the above logic in Python:
def is_prime(n): if n < 2: return False for i in range(2, n): if n %% i == 0: return False return True
In the above code, we first check if the given number is less than 2.
If it is less than 2, then it is not a prime number, so we return False.
Otherwise, we iterate through all the numbers from 2 to n-1 using a for loop.
If any number between 2 and n-1 divides n evenly, then we return False.
If we iterate through all the numbers from 2 to n-1 and do not find any number that divides n evenly, then we return True, indicating that the number is prime.
Let’s test our function with a few examples:
print(is_prime(5)) # True print(is_prime(10)) # False print(is_prime(23)) # True print(is_prime(1)) # False
In conclusion, we have written a simple Python program to check whether a given number is prime or not.
This program can be useful in many applications where prime numbers are required, such as cryptography or generating secure keys.