Exercice 69

Write an algorithm as a function in Python which takes two integers a and b as arguments and returns True if the numbers a and b are coprime and False if not.

Solution


def coprimeTest (n, m):
# define counter which counts the number of common divisors for m and n
numberDiv = 0
for i in range (1, n + 1):
# If i is a common divisor for m and n , we increment the numDiv counter
if (m% i == 0 and n% i == 0):
numberDiv = numberDiv + 1
# If the number of common divisors for m and n is = 1
# then m and n are coprime
if (numberDiv == 1):
return True
else:
return False
# Testing the algorithm
print (coprimeTest (5,7)) # prints True because 5 and 7 are coprime
print (coprimeTest (8, 12)) # prints False because 8 and 12 are not prime to each other

Younes Derfoufi
my-courses.net

Leave a Reply