-1

It is giving very big vales when I tested it for 2,20 range and taking a lot of time for 2 million. What can be wrong?

i=2
sum=0
for a in range(2,2000001):
     for i in range (2,a):
        if a%i==0:   
            break
        else:
            sum=sum+a
print (sum)
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 5
    That's about the slowest way of finding prime numbers that you could have used. Find a better algorithm, like the Sieve of Eratosthenes. – Mark Ransom Aug 21 '20 at 16:51
  • 1
    @MarkRansom, it's not just slow, it's wrong. if he wanted to sum all prime numbers, the sum should be in another condition outside the inner for. – Yasin Yousif Aug 21 '20 at 17:01
  • Hi Muhammad, welcome! StackOverflow is not meant for this type of question, where you need help getting to grips with programming - maybe look for a discussion board for that. – Arthur Tacca Aug 21 '20 at 17:03
  • @YasinYousif good point, but I read the question as being about slowness not correctness. – Mark Ransom Aug 21 '20 at 17:05
  • This is the exact probem of Project Euler #10. As others wrote, read a bit about algorithms to produce primes. You wouldn't have written this code if you had. – trincot Aug 21 '20 at 18:21

1 Answers1

1

You can use SymPy to get the prime numbers using Sieve of Eratosthenes, then sum() to add them.

To pip install SymPy, use the pip command in your terminal:

pip install sympy

Visit their installation page to see other methods of installing.

The SymPy documentation for prime number related functions explains how to use their assortment of functions.

This simple code will accomplish what you want:

from sympy import sieve
sieve.extend(2000000)
print(sum(sieve._list))

And will print:

142913828922
Elan-R
  • 484
  • 3
  • 6
  • (Note that this code ran in a few seconds on my computer, so if it's taking a while then you might have forgotten `._list`, in which the code is summing all primes to infinity.) – Elan-R Aug 21 '20 at 17:21
  • I wouldn't have guessed that prime numbers fell under the scope of `SymPy`. Although using it does feel like cheating. – Mark Ransom Aug 21 '20 at 17:41
  • If you want you could look at the math behind it and try to reproduce it in Python, but even so SymPy would be very useful in calculating that. – Elan-R Aug 21 '20 at 18:01