To check if a given number is prime, you can write a Python program using the following steps:
- Get the input number from the user.
- Check if the input number is less than 2. If it is, print that it is not a prime number and stop the program.
- Iterate from 2 to the square root of the input number (inclusive) using a
for
loop. - Check if the input number is divisible by any number in the iteration.
- If it is divisible, print that it is not a prime number and stop the program.
- If none of the numbers divide the input number, it is a prime number.
- If the loop completes without finding a divisor, print that the input number is a prime number.
Here’s the complete code for the program:
import math
# Step 1: Get input number from the user
num = int(input("Enter a number: "))
# Step 2: Check if the number is less than 2
if num < 2:
print(num, "is not a prime number.")
exit()
# Step 3: Iterate from 2 to the square root of the number
for i in range(2, int(math.sqrt(num)) + 1):
# Step 4: Check if the number is divisible by i
if num % i == 0:
print(num, "is not a prime number.")
exit()
# Step 5: The number is prime
print(num, "is a prime number.")
Now you can run the program, enter a number, and it will tell you whether the number is prime or not.
+ There are no comments
Add yours