Exercise 15
Write a Python program that asks the user to enter an integer n and determines whether n is prime or not.
Solution
# function to check if a number is prime def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True # main program n = int(input("Enter an integer: ")) if is_prime(n): print(n, "is a prime number") else: print(n, "is not a prime number")
In this algorithm:
- We define a function called is_prime: that takes an integer n as an argument and returns True if n is prime and False otherwise.
- The function checks if n is less than 2: (since 0 and 1 are not prime), and then loops through all numbers from 2 to the square root of n, checking if any of them divide n evenly.
- If a number is found that divides n evenly: then n is not prime and the function returns False.
- If the loop completes without finding a divisor for n: then n is prime and the function returns True.
- In the main program: we first ask the user to enter an integer n using the input function and convert it to an integer using int.
- Then, we call the is_prime function: with n as an argument and print the result depending on whether n is prime or not.
Younes Derfoufi
CRMEF OUJDA
[…] Exercise 15 * || Solution […]