Exercise 760
Write an algorithm in python as a function that finds the list of all prime divisors of a given integer n.
Solution
# creating a function to test primality of given number
def testPrimality(n):
# initializing the number of divisors of n
numberDivisors = 0
for i in range(1 , n + 1):
# we test if i is a divisor of n
if n%i == 0:
# and then we increment the number of divisors
numberDivisors = numberDivisors + 1
# the number n is prim if and only if admits exactly two divisors 1 and itself
if numberDivisors == 2:
return True
else:
return False
# creating a function that returns the list of prim divisors of n
def listPrimDivisors(n):
# initializing the list of prim divisors
primDivisors = []
for i in range(1 , n + 1):
if( n%i == 0 and testPrimality(i)):
primDivisors.append(i)
return primDivisors
# Testing algorithm
print("List of all prim divisors of 42 is : listPrimDivisors(42) = " , listPrimDivisors(42))
# The output is : List of all prim divisors of 42 is : listPrimDivisors(42) = [2, 3, 7]
Younes Derfoufi
my-courses.net
my-courses.net