16
\$\begingroup\$

I'm surprised that this challenge isn't already here, as it's so obvious. (Or I'm surprised I couldn't find it and anybody will mark it as a duplicate.)

Task

Given a non-negative integer \$n\$, calculate the sum of the first \$n\$ primes and output it.

Example #1

For \$n = 5\$, the first five primes are:

  • 2
  • 3
  • 5
  • 7
  • 11

The sum of these numbers is \$2 + 3 + 5 + 7 + 11 = 28\$, so the program has to output \$28\$.

Example #2

For \$n = 0\$, the "first zero" primes are none. And the sum of no numbers is - of course - \$0\$.

Rules

  • You may use built-ins, e.g., to check if a number is prime.
  • This is , so the lowest number of bytes in each language wins!
\$\endgroup\$

33 Answers 33

1
2
0
\$\begingroup\$

Japt -mx, 8 bytes

T=_j}a°T

Try it

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Pyth, 5 bytes

s.fP_

Try it online here.

s.fP_ZQ   Implicit: Q=eval(input())
          Trailing ZQ inferred
 .f   Q   Starting at Z=1, return the first Q numbers where...
   P_Z    ... Z is prime
s         Sum the resulting list, implicit print
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Reticular, 52 40 bytes

indQ2j;o_1-2~d:^=[d@P~1-]:^`*[+]:^`1+*o;

Try it online!

Explanation

Fun fact: Reticular does not count 2 as a prime number, so the instruction @P which gives the \$n\$-th prime in reality gives the \$(n+1)\$-th prime and due to this we have to add the first prime 2 manually.

in           # Read input and convert to int
dQ2j;o_      # Check if input is 0. If so, output and exit
1-2~d:^=     # Subtract 1 from input and save it as  `^`
[d@P~1-]     # Duplicate the top of the stack (call it k)
               and push the k-th prime. Finally swap the two top items
               in the stack and subtract 1.
               Stack before: [k]
               Stack after: [k-1, k-th prime]
:^`*         # Repeat the above a `^` number of times. 
               Stack before: [n]
               Stack after: [0, 3, 5, ...,  n-th prime, 2]
[+]:^`1+*    # Add the two top items in the stack a
               total of (`^`+1) number of times
o;           # Output the sum and exit.
| improve this answer | |
\$\endgroup\$
1
2

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.