0
$\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$
  • $\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 Apr 28 '14 at 11:21
1
$\begingroup$
sage: sum([x for x in range(4000001,5000000,2) if x in Primes()])
294095048847
$\endgroup$
  • $\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$ – Yuval Filmus Apr 28 '14 at 1:14
  • $\begingroup$ Pari: t=0; forprime(p=4000000,5000000,t=t+p); t $\endgroup$ – DanaJ Apr 29 '14 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 Apr 29 '14 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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