Exercise 754

Write a Python algorithm as a function that takes an integer n as argument and returns the smallest prime integer greater than or equal to n. Example for n = 8, the function returns the smallest prime number greater than or equal to 8 which is 11.

Solution

# creating function to test if given number is prim or not
def testPrim(m):
# Initializing number of divisors
numberDivisors = 0

# while i is divisor of m we increment numberDivisors
for i in range(1 , m + 1):
if(m%i == 0):
numberDivisors = numberDivisors + 1

# a number is prime if and only if it has two divisors, 1 and itself
if (numberDivisors == 2):
return True
else:
return False

def smallestPrim(n):
# initializing value of searched smallest prim p
p = n
while ( not testPrim(p) ):
p = p + 1
return p
# Testing algorithm
print("The smallest prim greater than or equal 18 is : " , smallestPrim(18))
# The output is : The smallest prim greater than or equal 18 is : 19

Younes Derfoufi
my-courses.net

Leave a Reply