# Algorithm to find and add prime numbers

How would one write code to find and add the prime numbers between 4 and 5 million? I need a code that can find all such numbers, and then add them together. I'm not too keen on computer science, so I wouldn't know even where to begin. (I'm a math major).

Any help is appreciated. Also any advice on how to compile and run the code would be helpful.

PS I know the answer is one of the following: 294185048443, 303141243820, 294095048847, 277319432363, 453190021165, or 210569014847.

• If you prefer Mathematica, you can do Total[Select[Table[n, {n, 4000000, 5000000}], PrimeQ]]. This gives the same answer as Yuval's sage code. It's not too smart, but it only takes 0.4 seconds to output the answer on my machine. – Juho Apr 28 '14 at 11:21

sage: sum([x for x in range(4000001,5000000,2) if x in Primes()])

• I don't know whether sage actually runs a sieve here, but the numbers are so small that this takes only a few seconds. – Yuval Filmus Apr 28 '14 at 1:14
• Pari: t=0; forprime(p=4000000,5000000,t=t+p); t – DanaJ Apr 29 '14 at 15:20
• Perl: use Math::Prime::Util "forprimes"; my $t = 0; forprimes {$t += $_ } 4e6,5e6; say$t; or less efficiently: use Math::Prime::Util "primes"; use List::Util "sum"; say sum(@{primes(4e6,5e6)}); Python: from sympy import sieve sum([x for x in sieve.primerange(4e6,5e6)]) – DanaJ Apr 29 '14 at 15:31