In: Computer Science
Write a Python program which takes a set of positive numbers from the input and returns the sum of the prime numbers in the given set. The sequence will be ended with a negative number.
Prime Numbers:
Prime numbers are the natural numbers that are greater than 1 and they have only two divisors: 1 and themselves. Some of the prime numbers are 2, 3, 5, 7, 11, 13, 17.....
Required Python program :
The program will take the set of positive numbers as input till the user enters any negative number and it will return the sum of all the prime numbers in the given set.
#Function to check whether the number is prime or not
#This will return true if the given number is prime otherwise false
def isPrime(num) :
if (num <= 1) :
return False
if (num <= 3) :
return True
if (num % 2 == 0 or num % 3 == 0) :
return False
i = 5
while(i * i <= num) :
if (num % i == 0 or num % (i + 2) == 0) :
return False
i = i + 6
return True
# Driver Program
#Initializing an empty list to store the set of numbers
list = []
print("Enter the elements : ")
element = 0
#Loop to take input till user enter a negative number
while(element >= 0):
element = int(input())
list.append(element) # adding the element
sum = 0
#Adding all the prime numbers from the given set
for i in list:
if(isPrime(i)):
sum += i
print(sum)
Sometimes, copying and pasting the code can result in indentation errors that's why the code screenshots are attached below for reference:
Output :
If you liked my answer, then please give me a thumbs up.