Question

What is the sum of all prime numbers between 1,000,000,000,000 and 1,000,000,100,000? this works out but is very slow.I need to optimize it.I am new to python. 3614000181007876 is the right answer

    A=10 ** 6
N=A+1
B=10 ** 5
prime=[]
sum=0
for i in range(0,N):
    prime.append(0)
for i in range(2,N):
    if(prime[i]==1):
        continue
    for j in range(i*i,N,i):
        prime[j]=1
for i in range((A ** 2)+1,(A ** 2)+B,2):
    for j in range(2,A):
        c=0
        if(prime[j]==1):
            continue
        if(i%j==0):
            c=c+1
            if(c>0):
                break
    if(c==0):
        #print(i)
        sum=sum+i


print(sum)
Was it helpful?

Solution

Not the most efficient way, but gets the right result (hopefully 3614000181007876) in 2 seconds on my box:

def isPrime(n):
    d = n - 1
    s = 0
    while not d & 1:
        s += 1
        d >>= 1
    for a in (2, 13, 23, 1662803):
        if pow(a, d, n) != 1 and all(pow(a, (1 << r) * d, n) != n - 1 for r in range(0, s)):
            return False
    return True

print(sum(x for x in range(1000000000001, 1000000100000, 2) if isPrime(x)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top