Exercise 67
Write a function in Python which takes as argument an integer n and which returns True if the number n is prime and False if n is not prime without using any predefined function.
Solution
def primNumber(n):
# take initial value of number of divisors
numberOfDivisors = 0
for i in range(1,n+1):
# while i is a divisor of n we increment we increment numberOfDivisors
if n%i == 0:
numberOfDivisors = numberOfDivisors + 1
# the integer n is a prim number only if numberOfDivisors == 2
if numberOfDivisors == 2:
return True
else:
return False
# Testing the function
print(primNumber(7)) # The output is True because 7 is a prim number
print(primNumber(6)) # The output is False because 6 is not a prim number
Younes Derfoufi
my-courses.net
my-courses.net
Thank you for sharing an amazing & wonderful blog. This content is very useful, informative and valuable in order to enhance knowledge. Keep sharing this type of content with us & keep updating us with new blogs. Apart from this, if anyone who wants to join the Python with machine-learning training institute in Delhi, can contact 9311002620 or visit our website-
https://www.htsindia.com/Courses/python/python-with-machine-learning-training-course