Summation of primes

 

Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Ans:-142913828922

Code:-

limit = 200001 
suml = [0] * limit 
a = [True] * limit 
a[0] = a[1] = False 
for i, isprime in enumerate(a): 
        if isprime: 
                suml[i] = suml[i-1] + i 
                for n in range(i*i, limit, i): 
                        a[n] = False 
        else: 
                suml[i] = suml[i-1] 

print(suml[2000000])

This problem is a programming version of Problem 10 from projecteuler.net On Hackerrank.com

The sum of the primes below 10 is 2+3+5+7=17 .

Find the sum of all the primes not greater than given N.

Input Format

The first line contains an integer T  i.e. number of the test cases.
The next T lines will contains an integer N.

Constraints

  • 1⩽T⩽ 104
  • 1⩽N⩽ 106

Output Format

Print the value corresponding to each test case in separate line.

Sample Input 

2
5
10

Sample Output 

10
17

Explanation 

  • For N=5, we have primes as {2,3,5}  and the sum is 10.
  • For N=10, we have primes as {2,3,5,7} and the sum is 17.

Code:-

import sys

limit = 100000
suml = [0] * limit
a = [True] * limit
a[0] = a[1] = False
for i, isprime in enumerate(a):
    if isprime:
        suml[i] = suml[i-1] + i
        for n in range(i*i, limit, i):
            a[n] = False
    else:
        suml[i] = suml[i-1]

t = int(input().strip())
for a0 in range(t):
    n = int(input().strip())
    print(suml[n])