def is_prime(number):
# Check if the number is less than 2
if number < 2:
return False
# Check for factors from 2 to the square root of the number
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
# If a factor is found, the number is not prime
return False
# If no factors are found, the number is prime
return True
# Example usage
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Explanation:
The is_prime function takes an integer number as an argument and returns True if the number is prime, and False otherwise.
The function first checks if the number is less than 2. If it is, the number is not prime, as prime numbers are defined as greater than 1.
It then uses a for loop to iterate over the range from 2 to the square root of the number (rounded up to the nearest integer). This is an optimization, as factors of a number larger than its square root must pair with factors smaller than its square root.
Inside the loop, it checks if the number is divisible evenly by the current value of i. If it is, then the number is not prime, and the function returns False.
If no factors are found in the loop, the function returns True, indicating that the number is prime.
Finally, an example usage of the function is shown, where the user is prompted to enter a number, and the program prints whether it is prime or not based on the result of the is_prime function.
0 Comments:
Post a Comment