Exercise 80

Write an algorithm in Python as a function which takes two numbers m and n as parameters (m < n) and which returns a list formed of all the prime numbers between m and n. Example for m = 10 and n=20  the function must return:

[11, 13, 17, 19]

Solution


def primNumber(n):
# take initial value of number of divisors
numberOfDivisors = 0
for i in range(1,n+1):

# while i is a divisor of n we increment we increment numberOfDivisors
if n%i == 0:
numberOfDivisors = numberOfDivisors + 1
# the number n is prim number only if numberOfDivisors == 2
if numberOfDivisors == 2:
return True
else:
return False

# Now we can find the set of the prims numbers in given intervall [m,n]
def listPrimNumbers(m,n):
listPrim = []
for i in range(m , n+1):

# we test if i is prim or not
if (primNumber(i)):
# we add i to the list if it is a prim number
listPrim.append(i)
return listPrim

# Testing the function
print(listPrimNumbers(10,20))
# The output is [11, 13, 17, 19]
Younes Derfoufi
my-courses.net

Leave a Reply