Monday, March 11, 2024

BCA PART A 5. Check if a given number is a Prime Number or not

 def is_prime(number):

# Check if the number is less than 2 (not a prime number)
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:
return False
return True

# Get input from the user
num = int(input("Enter a number to check if it's prime: "))

# Call the function to check if the number is prime
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Output 1:
Enter a number to check if it's prime: 121 121 is not a prime number.

Output 2:
Enter a number to check if it's prime: 17 17 is a prime number.

Explanation :

Function Definition:

This line defines a function named is_prime that takes a parameter number. The function will return True if the number is prime and False otherwise.

Check for Numbers Less than 2:

This block of code checks if the input number is less than 2. If so, it immediately returns False since prime numbers are defined as greater than 1.

Check for Factors:

This loop checks for factors of the number from 2 up to the square root of the number. If any factor is found, the function returns False since the number is not prime.

Return True for Prime Numbers:

If the loop completes without finding any factors, the function returns True, indicating that the number is prime.

User Input:

This line prompts the user to enter a number for prime checking.

Function Call and Output:

This block of code calls the is_prime function with the user-provided number and prints the result based on whether the number is prime or not.


No comments:

Post a Comment