Exercise 213

Write a python program that determines the set of prime numbers from 1 to 100.

Solution

#function that tests the primality of a number
def testPrim(n):
# initialization of the number of divisors of n
numberDiv = 0
for i in range(1,n+1):
# if i is a divisor of n we increment the number of divisors
if n%i == 0:
numberDiv = numberDiv + 1
# number n is prime if and only if numberDiv == 2
if numberDiv == 2:
return True
else:
return False

# initialization of the set of prime numbers from 1 to 100
A = set({})

# iterate through the set of integers from 1 to 100
for i in range(1 , 101):
if testPrim(i):
A.add(i)

# display the set of prime numbers
print("A = ", A)
"""
output:
A = {2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97}
"""
Younes Derfoufi
my-courses.net

Leave a Reply