Answer to Question #179421 in Python for CHANDRASENA REDDY CHADA

Question #179421

Sum of Prime Numbers In the Input

Given a list of integers, write a program to print the sum of all prime numbers in the list of integers.

Note: One is neither prime nor composite number.Input


The input will be a single line containing space-separated integers..Output


The output should be a single line containing the sum of all prime numbers from 1 to N.Explanation


For example, if the given list of integers are

2 4 5 6 7 3 8


As 2, 3, 5 and 7 are prime numbers, your code should print the sum of these numbers. So the output should be 17.


Sample Input 1

2 4 5 6 7 3 8


Sample Output 1

17


Sample Input 2

65 87 96 31 32 86 57 69 20 42


Sample Output 2

31




1
Expert's answer
2021-04-08T02:59:07-0400
# Program to computer sum
# of prime number in a given range


# from math lib import sqrt method
from math import sqrt


# Function to compute the prime number
# Time Complexity is O(sqrt(N))
def checkPrime(numberToCheck) :


	if numberToCheck == 1 :
		return False


	for i in range(2, int(sqrt(numberToCheck)) + 1) :


		if numberToCheck % i == 0 :
			return False


	return True


# Function to iterate the loop
# from l to r. If the current
# number is prime, sum the value
def primeSum(l, r) :


	sum = 0


	for i in range(r, (l - 1), -1) :


		# Check for prime
		isPrime = checkPrime(i)
		
		if (isPrime) :


			# Sum the prime number
			sum += i


	return sum


# Time Complexity is O(r x sqrt(N))


# Driver code	
if __name__ == "__main__" :


	l, r = 4, 13


	# Call the function with l and r
	print(primeSum(l, r))




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS