- 1

This is the question I m having problem in "write a function sumprimes(l) that takes as input a list of integers and returns the sum of all the prime numbers in l".

here r some examples to show how your function should work >>>sumprimes([3,3,1,13]) 19 >>>sumprimes([-3,1,6]) 0 here is my solution def sumprimes(l): sum=0 for i in range (0,len(l)): num=l[i] if num >1: prime= True for j in range(2,int(num**0.5)+1): if(num%j==0): prime=False break if prime: sum=sum+num else : sum=0 return sum the problem with me is that sumprimes([17,51,29,39]) is giving output 0 instead of 46 & sumprimes([3,3,1,13]) is giving correct output which is 19 and gives correct output also for ([2,4,6,9,11]) nd ([-3,1,6]) plz tell me where my mistake is nd what might correct it

3rd Aug 2016, 6:15 PM
Vipul Jain
Vipul Jain - avatar
4 Respostas
+ 1
def sumprimes(l): primeNum = [] for item in l: is_prime = True if(item >= 2): maxInt = int(item ** 0.5) + 1 for i in range(2, maxInt): if(item % i == 0): is_prime = False break if(is_prime): primeNum.append(item) return(sum(primeNum)) Input: print(function([1, 2, -3, 4, 5, 6, 27, 36, 21, 19, 47])) Output: > 73 Input: print(function([-3, 1, 6])) Output: > 0
2nd Feb 2017, 4:40 PM
rishu anand
rishu anand - avatar
0
def sumprimes(l): s=0 m=len(l) for i in range(0,m): num=l[i] if(num>1): prime="true" for j in range(2,num): if num%j==0: prime="false" break if prime=="true": s=s+num return(s)
19th Aug 2018, 11:00 AM
Naga Mahendra
Naga Mahendra - avatar
0
def get_primes(): num = 2 while True: f is_prime(num): yield num num += 1
7th Oct 2019, 12:41 AM
Edwin Cancel
Edwin Cancel - avatar
- 1
I couldn't reproduce your errors, so your list may have problems also. Whenever your number is not dividable by an integer between 1 and the number and prime is still true, your result counts up. you should move the if prime check outsde of the loop. In your example 3 is not even added. Also because primes above 2 must always be odd, you could do an initial number%2 == 0. This would remove about 60% workload for bigger numbers. And if you want to speed it up even more, you could implement trial division. def sumprimes(l): sum=0 for i in l: if i >1: prime= true for j in range(2,int(i**0.5)+1): if(i%j==0): prime=False break #move this part of the loop if prime: sum+=i #this is never reached, so remove this else : sum=0 #move the check if prime true here if... return sum
3rd Aug 2016, 9:25 PM
Frederik Fleischmann
Frederik Fleischmann - avatar