How to Calculate Sum of Prime Numbers from List of Integers in Python

How to calculate sum of prime numbers from list of integers in Python?

This part is wrong:

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

you are summing num for each number in the range that didn't divide.
you should sum just if all of them didn't divide.

Simple way to do this is:

        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 in a more pythonic way using all():

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

Finding the sum of prime Numbers in a List in Python

You'd better create a function to test if number is prime as @wim said.

def is_prime(n):
if n < 2:
return False
elif n <= 3:
return True
elif n % 2 == 0:
return False

# round up the sqrt of n
length = int(n**.5) + 1 # n**.5 is equal to sqrt(n)
for i in range(3, length, 2):
if n % i == 0:
return False

return True

This is a simple and efficient primality test.
Then you can simply sum with:

def sum_primes(l):
return sum(n for n in l if is_prime(n))

Sum of all prime numbers between 1 and N in Python

This is the most broken part of your code, it's doing the opposite of what you want:

res = x%y
if res==0:
sum = sum + x
break

You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:

from math import sqrt

T = int(input())

for _ in range(T):
N = int(input())

sum_of_primes = 0

if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2

for number in range(3, N + 1, 2):

for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number

print(sum_of_primes)

OUTPUT

> python3 test.py
3
5
10
10
17
23
100
>

Calculate the sum of all primes below two million - code takes too long

Sieve of Eratosthenes is one of the best algorithm of finding all prime numbers below some number.

Basicly you create a list of booleans with the size of range 2 to whatever number you want. Then you remove all the indexes of each true values index folds. Such as after you start searching list you came across 2 and you update to false all the indexes of 2*n then you jump to 3 then you update all 3*n indexes to false. Then you skip 4 since you have already updated it to false. Then you came to 5 and replace all 5*n to false. End so on. At the and you will get a long list that all true valued indexes are prime number. You can use this list as you want.

A basic algorithm as pointed out by Wikipedia would be:

 Let A be an array of Boolean values, indexed by integers 2 to n, 
initially all set to true.

for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
A[j] := false.
Output: all i such that A[i] is true.

python sum of primes

Your d variable is being reset during each iteration of your outer loop. Move the initialization out of that loop.

Additionally, the a == 2 check should only occur once per iteration of the outer loop. Move it out of the inner loop.

b=1
d = 0
#generates a list of numbers.
while b<100:
b=b+1
x = 0.0
a = 0
#generates a list of numbers less than b.
while x<b:
x=x+1
#this will check for divisors.
if (b/x)-int(b/x) == 0.0:
a=a+1
if a==2:
#if it finds a prime it will add it.
d=d+b
print d

Result:

1060

While we're at it, let's try cleaning up the code so it's more comprehensible. You can move the inner loop into its own function, so readers can more clearly understand its purpose:

def is_prime(b):
x = 0.0
a = 0
while x<b:
x=x+1
#this will check for divisors.
if (b/x)-int(b/x) == 0.0:
a=a+1
if a==2:
return True
else:
return False

b=1
d=0
#generates a list of numbers.
while b<100:
b=b+1
if is_prime(b):
d=d+b
print d

It's also useful to use variable names that describe what they represent:

def is_prime(number):
candidate_factor = 0
amount_of_factors = 0
while candidate_factor<number:
#A += B is equivalent to A = A + B
candidate_factor += 1
#A little easier way of testing whether one number divides another evenly
if number % candidate_factor == 0:
amount_of_factors += 1
if amount_of_factors == 2:
return True
else:
return False

number=1
prime_total=0
#generates a list of numbers.
while number<100:
number += 1
if is_prime(number):
prime_total += number
print prime_total

for loops are more idomatic than while loops that increment a counter:

def is_prime(number):
amount_of_factors = 0
for candidate_factor in range(1, number+1):
if number % candidate_factor == 0:
amount_of_factors += 1
if amount_of_factors == 2:
return True
else:
return False

prime_total=0
#generates a list of numbers.
for number in range(2, 101):
if is_prime(number):
prime_total += number
print prime_total

If you're feeling bold, you can use list comprehensions to cut down on the number of loops you use:

def is_prime(number):
factors = [candidate_factor for candidate_factor in range(1, number+1) if number % candidate_factor == 0]
return len(factors) == 2

#generates a list of numbers.
primes = [number for number in range(2, 101) if is_prime(number)]
prime_total = sum(primes)
print prime_total

Print series of prime numbers in python

You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n).
If n is divisible by any of the numbers, it is not prime. If a number is prime, print it.

for num in range(2,101):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print (num)

You can write the same much shorter and more pythonic:

for num in range(2,101):
if all(num%i!=0 for i in range(2,num)):
print (num)

As I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n):

import math
for num in range(2,101):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)

For small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.

You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. Like so:

import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)

Edited:

As in the first loop odd numbers are selected, in the second loop no
need to check with even numbers, so 'i' value can be start with 3 and
skipped by 2.

import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(3,int(math.sqrt(num))+1, 2)):
print (num)

Sum of prime numbers between a given interval

You were adding i on every loop iteration(whether there are any factors other than 1 and itself). Instead, add i only when the factor is 1 and i:

x=int(input("lower limit"))
y=int(input("upper limit"))
s=0
for i in range(x, y+1):
for j in range(2,int(i ** (0.5))+1):
if i % j == 0:
break
else:
s += i
print(s)

Output:

lower limit2
upper limit10
17


Related Topics



Leave a reply



Submit