## Thursday, September 17, 2020

Solution Exercise 756 : algorithm python to find the largest prim number

#### Exercise 756

Write a Python algorithm as a function that takes an integer n as argument and returns the largest prime integer less than or equal to n. Example for n = 15, the function returns the largest prime number less than or equal to 15 which is 13.

#### 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 greatestPrim(n):
# initializing value of searched smallest prim p
p = n
while ( not testPrim(p) ):
p = p - 1
return p
# Testing algorithm
print("The geatest prim less than or equal 15 is : " , greatestPrim(15))
# The output is : The geatest prim less than or equal 15 is :  13
``````

Younes Derfoufi
my-courses.net 