1
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$
    – Juho
    Commented Apr 28, 2014 at 11:21

1 Answer 1

1
$\begingroup$
sage: sum([x for x in range(4000001,5000000,2) if x in Primes()])
294095048847
$\endgroup$
3
  • $\begingroup$ I don't know whether sage actually runs a sieve here, but the numbers are so small that this takes only a few seconds. $\endgroup$ Commented Apr 28, 2014 at 1:14
  • $\begingroup$ Pari: t=0; forprime(p=4000000,5000000,t=t+p); t $\endgroup$
    – DanaJ
    Commented Apr 29, 2014 at 15:20
  • $\begingroup$ 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)]) $\endgroup$
    – DanaJ
    Commented Apr 29, 2014 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.