A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. In other words, a prime number is a number that can only be evenly divided by 1 and itself.
For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, and 31 are the first few prime numbers. Note that 1 is not considered a prime number, as it only has one positive divisor (1) and does not meet the definition of a prime number.
Here's a Python program to check if a given number is prime or not:
python# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Get the number to check from the user
num = int(input("Enter a number: "))
# Check if the number is prime
if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
In this program, I first define a function is_prime()
to check if a number is prime or not. This function takes a number n
as input and returns True
if it's prime, or False
if it's not.
I then ask the user to enter a number to check. I call the is_prime()
function on the number, and print a message indicating whether it's prime or not based on the function's return value.
Note that I use the square root of n
to limit the number of divisors I need to check in the is_prime()
function, as any factor of n
greater than sqrt(n)
must have a corresponding factor less than sqrt(n)
to form a pair.
No comments:
Post a Comment