# Solution Exercise 15: python algorithm to check whether a given integer is prime or not

Mar 6, 2023

#### 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:

1. 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.
2. 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.
3. If a number is found that divides n evenly: then n is not prime and the function returns False.
4. If the loop completes without finding a divisor for n: then n is prime and the function returns True.
5. 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.
6. 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