Prime numbers are an important concept in programming and mathematics. In this blog, we will learn how to check whether a number is prime using a simple Python program.
What is a Prime Number?
A prime number is a number that has only two factors:
- 1
- The number itself
For example:
2, 3, 5, 7, 11, 13, 17, 19
are prime numbers.
But 4 is not prime because it can be divided by 1, 2, and 4.
Python Program
def prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
for n in range(10, 21):
if prime(n):
print(n)
How Does the Program Work?
1. Create a function
def prime(n):
This creates a function called prime() that takes a number n.
2. Check numbers from 2
for i in range(2, n):
The loop checks numbers starting from 2 up to n - 1.
3. Check divisibility
if n % i == 0:
The % operator gives the remainder.
If the remainder is 0, the number can be divided exactly by i.
So, the number is not prime.
4. Return False
return False
If a divisor is found, the function returns False.
5. Return True
return True
If no divisor is found, the number is prime, so the function returns True.
6. Check numbers from 10 to 20
for n in range(10, 21):
This checks every number from 10 to 20.
7. Print prime numbers
if prime(n):
print(n)
If the number is prime, it will be printed.
Output
11
13
17
19
Conclusion
Finding prime numbers is a good beginner programming exercise. It helps us understand:
- Functions
-
forloops -
ifconditions - The
%operator -
returnstatements
Top comments (0)