0 votes
1 view
in Python by (12k points)

I'm struck and need assistance with this. I need to discover the sum of prime numbers from a given list of whole numbers (Integers). Here are a couple of experiments for the equivalent.

n([3,3,1,13])

19

n([2,4,6,9,11])

13

n([-3,0,1,6])

0

Just look at the below code, but it fails in the test cases above.

def sumprimes(n):

    sum1 = 0

    for i in range(0,len(n)):

        num = n[i]

        if num > 1:

            for j in range(2, int(num**0.5)+1):

                if num%j != 0:

                    sum1 = sum1 + num

        else:

            sum1 = 0

    return(sum1)

1 Answer

0 votes
by (24.9k points)

Here, This part is actually wrong:

        for j in range(2, int(num**0.5)+1):

            if num%j != 0:

                sum1 = sum1 + num

you are adding num for each number in the range that didn't partition. you should sum just if every one of them didn't separate(divide).

Just simply try:

        prime = True

        for j in range(2, int(num**0.5)+1):

            if num%j == 0:

                prime = False

                break

        if prime:

            sum1 = sum1 + num

Or try using all():

        if all(num%j != 0 for j in range(2, int(num**0.5)+1)):

            sum1 = sum1 + num

Wanna become a Python expert? Come and join the python certification course and get certified.

Watch this video tutorial for more information

Related questions

0 votes
2 answers
0 votes
1 answer
asked Jul 25, 2019 in Python by Eresh Kumar (45.1k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...