Calculate the sum of the first n prime numbers

16

3

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!

xanoetux

Posted 2018-08-07T06:39:43.270

Reputation: 435

Related old challenge: First N primes in O(x^2) or less complexity. – Kevin Cruijssen – 2018-08-07T06:50:49.763

4Very closely related - Sum of primes between given range – Jonathan Allan – 2018-08-07T07:04:12.257

2OEIS - A7504 (aside: LOL at this in the formulas section, "a(n) = A033286(n) - A152535(n).") – Jonathan Allan – 2018-08-07T07:06:45.503

@JonathanAllan: Related, but not equivalent. I think it's an important difference if you check primes in range or a number of primes. What both tasks have in common is a) check if a number is prime and b) sum up numbers - which is common to many code-golf tasks here. – xanoetux – 2018-08-07T07:11:58.667

Yep, that is what "related" means otherwise I would've said "possible duplicate" or, if I felt strongly enough I could have just closed as a duplicate myself. Do note, however, that some may actually consider it a duplicate (since the definition of a "duplicate" is not "this is exactly that" but rather "submissions to this could be trivially ported to that" - so this would come down to one's interpretation of "trivially"). – Jonathan Allan – 2018-08-07T07:16:52.363

After a quick check of some of the answers of the challenge linked by Jonathan Allan I do think it is a dupe, as removing the first argument and hard coding it as 1 seems to lead to competitive solutions. – Laikoni – 2018-08-07T09:02:44.320

3

Also relevant: Things to avoid when writing challenges: The prime numbers.

– Laikoni – 2018-08-07T09:05:22.840

@Laikoni: Yes, you're right. My next challenge won't be about primes :-) – xanoetux – 2018-08-07T13:38:14.803

@xanoetux I'm fine with it, finally convinced me to compute prime numbers on the 6502 just for fun ;) – Felix Palmen – 2018-08-07T13:40:28.840

@Laikoni: This would be invalid, since primes in [1,3] = {2,3} and the first 3 primes are {2,3,5}, so for some languages it might be "quite" different. – ბიმო – 2018-08-09T00:17:47.327

Answers

15

6502 machine code routine, 75 bytes

A0 01 84 FD 88 84 FE C4 02 F0 32 E6 FD A0 00 A5 FD C9 04 90 1F 85 64 B1 FB 85
65 A9 00 A2 08 06 64 2A C5 65 90 02 E5 65 CA D0 F4 C9 00 F0 DC C8 C4 FE D0 DB
A5 FD A4 FE 91 FB C8 D0 C8 A9 00 18 A8 C4 FE F0 05 71 FB C8 D0 F7 60

Expects a pointer to some temporary storage in $fb/$fc and the number of primes to sum up in $2. Returns the sum in A (the accu register).

Never did some prime checks in 6502 machine code, so here it finally comes ;)

Note this starts giving wrong results for inputs >= 14. This is because of overflow, the code works with the "natural" number range of the 8bit platform which is 0 - 255 for unsigned.

Commented disassembly

; function to sum the first n primes
;
; input:
;   $fb/$fc: pointer to a buffer for temporary storage of primes
;   $2:      number of primes to sum (n)
; output:
;   A:       sum of the first n primes
; clobbers:
;   $fd:     current number under primality test
;   $fe:     number of primes currently found
;   $64:     temporary numerator for modulo check
;   $65:     temporary divisor for modulo check
;   X, Y
 .primesum:
A0 01       LDY #$01            ; init variable for ...
84 FD       STY $FD             ; next prime number to test
88          DEY                 ; init number of found primes
 .mainloop:
84 FE       STY $FE             ; store current number of found primes
C4 02       CPY $02             ; compare with requested number
F0 32       BEQ .sum            ; enough primes -> calculate their sum
 .mainnext:
E6 FD       INC $FD             ; check next prime number
A0 00       LDY #$00            ; start check against first prime number
 .primecheckloop:
A5 FD       LDA $FD             ; load current number to check
C9 04       CMP #$04            ; smaller than 4?
90 1F       BCC .isprime        ; is a prime (shortcut to get list started)
85 64       STA $64             ; store to temp as numerator
B1 FB       LDA ($FB),Y         ; load from prime number table
85 65       STA $65             ; store to temp as divisor
A9 00       LDA #$00            ; init modulo to 0
A2 08       LDX #$08            ; iterate over 8 bits
 .bitloop:
06 64       ASL $64             ; shift left numerator
2A          ROL A               ; shift carry into modulo
C5 65       CMP $65             ; compare with divisor
90 02       BCC .bitnext        ; smaller -> to next bit
E5 65       SBC $65             ; otherwise subtract divisor
 .bitnext:
CA          DEX                 ; next bit
D0 F4       BNE .bitloop
C9 00       CMP #$00            ; compare modulo with 0
F0 DC       BEQ .mainnext       ; equal? -> no prime number
C8          INY                 ; next index in prime number table
C4 FE       CPY $FE             ; checked against all prime numbers?
D0 DB       BNE .primecheckloop ; no -> check next
 .isprime:
A5 FD       LDA $FD             ; prime found
A4 FE       LDY $FE             ; then store in table
91 FB       STA ($FB),Y
C8          INY                 ; increment number of primes found
D0 C8       BNE .mainloop       ; and repeat whole process
 .sum:
A9 00       LDA #$00            ; initialize sum to 0
18          CLC
A8          TAY                 ; start adding table from position 0
 .sumloop:
C4 FE       CPY $FE             ; whole table added?
F0 05       BEQ .done           ; yes -> we're done
71 FB       ADC ($FB),Y         ; add current entry
C8          INY                 ; increment index
D0 F7       BNE .sumloop        ; and repeat
 .done:
60          RTS

Example C64 assembler program using the routine:

Online demo

Code in ca65 syntax:

.import primesum   ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    4               ; maximum length of a valid unsigned
                                        ; 8-bit number input
convbuf:        .res    3               ; 3 BCD digits for unsigned 8-bit
                                        ; number conversion
primebuf:       .res    $100            ; buffer for primesum function

.data
prompt:         .byte   "> ", $0
errmsg:         .byte   "Error parsing number, try again.", $d, $0

.code
                lda     #$17            ; set upper/lower mode
                sta     $d018

input:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #4
                jsr     readline

                lda     linebuf         ; empty line?
                beq     input           ; try again

                lda     #<linebuf       ; convert input to int8
                ldy     #>linebuf
                jsr     touint8
                bcc     numok           ; successful -> start processing
                lda     #<errmsg        ; else show error message and repeat
                ldy     #>errmsg
                jsr     $ab1e
                bcs     input

numok:          
                sta     $2
                lda     #<primebuf
                sta     $fb
                lda     #>primebuf
                sta     $fc
                jsr     primesum        ; call function to sum primes
                tax                     ; and ...
                lda     #$0             ; 
                jmp     $bdcd           ; .. print result

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear 
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear 
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

; parse / convert uint8 number using a BCD representation and double-dabble
.proc touint8
                sta     $fb
                sty     $fc
                ldy     #$0
                sty     convbuf
                sty     convbuf+1
                sty     convbuf+2
scanloop:       lda     ($fb),y
                beq     copy
                iny
                cmp     #$20
                beq     scanloop
                cmp     #$30
                bcc     error
                cmp     #$3a
                bcs     error
                bcc     scanloop
error:          sec
                rts
copy:           dey
                bmi     error
                ldx     #$2
copyloop:       lda     ($fb),y
                cmp     #$30
                bcc     copynext
                cmp     #$3a
                bcs     copynext
                sec
                sbc     #$30
                sta     convbuf,x
                dex
copynext:       dey
                bpl     copyloop
                lda     #$0
                sta     $fb
                ldx     #$8
loop:           lsr     convbuf
                lda     convbuf+1
                bcc     skipbit1
                ora     #$10
skipbit1:       lsr     a
                sta     convbuf+1
                lda     convbuf+2
                bcc     skipbit2
                ora     #$10
skipbit2:       lsr     a
                sta     convbuf+2
                ror     $fb
                dex
                beq     done
                lda     convbuf
                cmp     #$8
                bmi     nosub1
                sbc     #$3
                sta     convbuf
nosub1:         lda     convbuf+1
                cmp     #$8
                bmi     nosub2
                sbc     #$3
                sta     convbuf+1
nosub2:         lda     convbuf+2
                cmp     #$8
                bmi     loop
                sbc     #$3
                sta     convbuf+2
                bcs     loop
done:           lda     $fb
                clc
                rts
.endproc

Felix Palmen

Posted 2018-08-07T06:39:43.270

Reputation: 3 866

4I enjoy this so much more than the constant stream of golfing languages (I may or may not be wearing a MOS 6502 t-shirt today). – Matt Lacey – 2018-08-08T01:55:31.750

1@MattLacey thanks :) I'm just too lazy to learn all these languages ... and doing some puzzles in 6502 code feels kind of "natural" because saving space is actually a standard programming practice on that chip :) – Felix Palmen – 2018-08-08T06:01:59.003

I need to buy a MOS 6502 T-Shirt. – Titus – 2018-08-08T11:52:27.837

8

Python 2, 49 bytes

f=lambda n,t=1,p=1:n and p%t*t+f(n-p%t,t+1,p*t*t)

Uses Wilson's theorem, (as introduced to the site by xnor, I believe here)

Try it online!

The function f is recursive, with an initial input of n and a tail when n reaches zero, yielding that zero (due to the logical and); n is decremented whenever t, a test number which increments with every call to f, is prime. The prime test is then whether \$(n-1)!\ \equiv\ -1 \pmod n\$ for which we keep a track of a square of the factorial in p.

Jonathan Allan

Posted 2018-08-07T06:39:43.270

Reputation: 67 804

I was adapting one of Lynn's common helper functions and achieved the exact same thing.

– Mr. Xcoder – 2018-08-07T08:14:08.283

...ah so the theorem was introduced to the site by xnor. Good reference post, thanks! – Jonathan Allan – 2018-08-07T08:30:56.217

7

Jelly, 4 bytes

My first Jelly program

RÆNS

Try it online!

Kroppeb

Posted 2018-08-07T06:39:43.270

Reputation: 1 558

2Nice, note that ÆN€S would also do it. – Jonathan Allan – 2018-08-07T12:33:59.750

6

05AB1E, 3 bytes

ÅpO

Try it online.

Explanation:

Åp     # List of the first N primes (N being the implicit input)
       #  i.e. 5 → [2,3,5,7,11]
  O    # Sum of that list
       #  i.e. [2,3,5,7,11] → 28

Kevin Cruijssen

Posted 2018-08-07T06:39:43.270

Reputation: 67 575

6

Java 8, 89 bytes

n->{int r=0,i=2,t,x;for(;n>0;r+=t>1?t+0*n--:0)for(t=i++,x=2;x<t;t=t%x++<1?0:t);return r;}

Try it online.

Explanation:

n->{               // Method with integer as both parameter and return-type
  int r=0,         //  Result-sum, starting at 0
      i=2,         //  Prime-integer, starting at 2
      t,x;         //  Temp integers
  for(;n>0         //  Loop as long as `n` is still larger than 0
      ;            //    After every iteration:
       r+=t>1?     //     If `t` is larger than 1 (which means `t` is a prime):
           t       //      Increase `r` by `t`
           +0*n--  //      And decrease `n` by 1
          :        //     Else:
           0)      //      Both `r` and `n` remain the same
    for(t=i++,     //   Set `t` to the current `i`, and increase `i` by 1 afterwards
        x=2;       //   Set `x` to 2
        x<t;       //   Loop as long as `x` is still smaller than `t`
      t=t%x++<1?   //    If `t` is divisible by `x`:
         0         //     Set `t` to 0
        :          //    Else:
         t);       //     `t` remains the same
                   //   If `t` is still the same after this loop, it means it's a prime
  return r;}       //  Return the result-sum

Kevin Cruijssen

Posted 2018-08-07T06:39:43.270

Reputation: 67 575

5

Brachylog, 8 7 bytes

~lṗᵐ≠≜+

Try it online!

Saved 1 byte thanks to @sundar.

Explanation

~l        Create a list of length input
  ṗᵐ      Each element of the list must be prime
    ≠     All elements must be distinct
     ≜    Find values that match those constraints
      +   Sum

Fatalize

Posted 2018-08-07T06:39:43.270

Reputation: 32 976

~lṗᵐ≠≜+ seems to work, for 7 bytes (Also, I'm curious why it gives output 2*input+1 if run without the labeling.) – sundar - Reinstate Monica – 2018-08-07T08:59:29.403

2@sundar I checked using the debugger and found why: it doesn't choose values for the primes, but it still knows that every single one must be in [2,+inf) obviously. Therefore, it knows that the sum of 5 primes (if the input is 5) must be at least 10, and it partially knows that because the elements must be different, they can't all be 2 so it's at least 11. TL;DR implementation of implicit labellization isn't strong enough. – Fatalize – 2018-08-07T09:16:41.080

That's very interesting. I like how the reason is not some quirk of syntax or random accident of implementation, but something that makes sense based on the constraints. Thanks for checking it out! – sundar - Reinstate Monica – 2018-08-08T14:57:26.213

5

Perl 6, 31 bytes

{sum grep(&is-prime,2..*)[^$_]}

Try it online!

The is-prime built-in is unfortunately long.

Jo King

Posted 2018-08-07T06:39:43.270

Reputation: 38 234

5

J, 8 bytes

1#.p:@i.

Try it online!

Galen Ivanov

Posted 2018-08-07T06:39:43.270

Reputation: 13 815

4

Husk, 4 bytes

Σ↑İp

Try it online!

Generates the İnfinite list of prime numbers, and computes the sum of the first \$N\$ (Σ↑)

Mr. Xcoder

Posted 2018-08-07T06:39:43.270

Reputation: 39 774

I believe it's İnteger sequence, İ€ is finite. – ბიმო – 2018-08-08T23:56:00.303

3

Attache, 10 bytes

Sum@Primes

Try it online!

ho hum

Conor O'Brien

Posted 2018-08-07T06:39:43.270

Reputation: 36 228

2

Retina, 41 bytes

K`_
"$+"{`$
$%"_
)/¶(__+)\1+$/+`$
_
^_

_

Try it online! I wanted to keep adding 1 until I had found n primes but I couldn't work out how to do that in Retina so I resorted to a nested loop. Explanation:

K`_

Start with 1.

"$+"{`

Loop n times.

$
$%"_

Make a copy of the previous value, and increment it.

)/¶(__+)\1+$/+`$
_

Keep incrementing it while it's composite. (The ) closes the outer loop.)

^_

Delete the original 1.

_

Sum and convert to decimal.

Neil

Posted 2018-08-07T06:39:43.270

Reputation: 95 035

2

MATL, 4 bytes

:Yqs

Try it online!

Explanation:

       % Implicit input: 5
:      % Range: [1, 2, 3, 4, 5]
 Yq    % The n'th primes: [2, 3, 5, 7, 11]
   s   % Sum: 28

Stewie Griffin

Posted 2018-08-07T06:39:43.270

Reputation: 43 471

2

PHP, 66 bytes

using my own prime function again ...

for(;$k<$argn;$i-1||$s+=$n+!++$k)for($i=++$n;--$i&&$n%$i;);echo$s;

Run as pipe with -nr or try it online.

breakdown

for(;$k<$argn;      # while counter < argument
    $i-1||              # 3. if divisor is 1 (e.g. $n is prime)
        $s+=$n              # add $n to sum
        +!++$k              # and increment counter
    )
    for($i=++$n;        # 1. increment $n
        --$i&&$n%$i;);  # 2. find largest divisor of $n smaller than $n:
echo$s;             # print sum

Titus

Posted 2018-08-07T06:39:43.270

Reputation: 13 814

same length, one variable less: for(;$argn;$i-1||$s+=$n+!$argn--)for($i=++$n;--$i&&$n%$i;);echo$s; – Titus – 2018-11-16T15:27:51.923

2

Haskell, 48 bytes

sum.(`take`[p|p<-[2..],all((>0).mod p)[2..p-1]])

Try it online!

Note: \p-> all((>0).mod p)[2..p-1] is not a valid prime check, since it is True for \$0,1\$ as well. But we can work around that by beginning with \$2\$, so in this case it suffices.

ბიმო

Posted 2018-08-07T06:39:43.270

Reputation: 15 345

2

C (gcc), 70 bytes

f(n,i,j,s){s=0;for(i=2;n;i++)for(j=2;j/i?s+=i,n--,0:i%j++;);return s;}

Try it online!

Curtis Bechtel

Posted 2018-08-07T06:39:43.270

Reputation: 601

Suggest n=s instead of return s – ceilingcat – 2018-08-14T21:57:13.380

2

Japt -x, 11 bytes

;@_j}a°X}hA

Try it online!

Saved several bytes thanks to a new language feature.

Explanation:

;@      }hA    :Get the first n numbers in the sequence:
     a         : Get the smallest number
      °X       : Which is greater than the previous result
  _j}          : And is prime
               :Implicitly output the sum

Kamil Drakari

Posted 2018-08-07T06:39:43.270

Reputation: 3 461

2

C, C++, D : 147 142 bytes

int p(int a){if(a<4)return 1;for(int i=2;i<a;++i)if(!(a%i))return 0;return 1;}int f(int n){int c=0,v=1;while(n)if(p(++v)){c+=v;--n;}return c;}

5 bytes optimization for C and C++ :

-2 bytes thanks to Zacharý

#define R return
int p(int a){if(a<4)R 1;for(int i=2;i<a;++i)if(!(a%i))R 0;R 1;}int f(int n){int c=0,v=1;while(n)if(p(++v))c+=v,--n;R c;}

p tests if a number is a prime, f sums the n first numbers

Code used to test :

C/C++ :

for (int i = 0; i < 10; ++i)
    printf("%d => %d\n", i, f(i));

D Optimized answer by Zacharý, 133 131 bytes

D has a golfy template system

T p(T)(T a){if(a<4)return 1;for(T i=2;i<a;)if(!(a%i++))return 0;return 1;}T f(T)(T n){T c,v=1;while(n)if(p(++v))c+=v,--n;return c;}

HatsuPointerKun

Posted 2018-08-07T06:39:43.270

Reputation: 1 891

1T p(T)(T a){if(a<4)return 1;for(T i=2;i<a;)if(!(a%i++))return 0;return 1;}T f(T)(T n){T c,v=1;while(n)if(p(++v)){c+=v;--n;}return c;}. Also, the C/C++/D can be int p(int a){if(a<4)return 1;for(int i=2;i<a;++i)if(!(a%i))return 0;return 1;}int f(int n){int c=0,v=1;while(n)if(p(++v)){c+=v;--n;}return c;} (same with the C/C++ optimization, just adjusting the algorithm abit) – Zacharý – 2018-11-10T02:32:26.273

Maybe for all the answers, you could use comma to make {c+=v;--n;} be c+=v,--n;? – Zacharý – 2018-11-12T15:07:30.680

Here's another one for D (and possibly for C/C++ as well, if reverted back to ints): T p(T)(T a){T r=1,i=2;for(;i<a;)r=a%i++?r:0;return r;}T f(T)(T n){T c,v=1;while(n)if(p(++v))c+=v,--n;return c;} – Zacharý – 2018-11-12T16:18:49.753

Suggest a>3&i<a instead of i<a and remove if(a<4)... – ceilingcat – 2018-11-20T17:17:25.367

1

JavaScript (ES6), 55 bytes

f=(k,n=2)=>k&&(g=d=>n%--d?g(d):d<2&&k--&&n)(n)+f(k,n+1)

Try it online!

Arnauld

Posted 2018-08-07T06:39:43.270

Reputation: 111 334

1

Stax, 6 bytes

ê☺Γ☼èY

Run and debug it

Explanation:

r{|6m|+ Unpacked program, implicit input
r       0-based range
 {  m   Map:
  |6      n-th prime (0-based)
     |+ Sum
        Implicit output

wastl

Posted 2018-08-07T06:39:43.270

Reputation: 3 089

1

APL (Dyalog Unicode), 7 + 9 = 16 bytes

+/pco∘⍳

Try it online!

9 additional bytes to import the pco (and every other) Dfn: ⎕CY'dfns'

How:

+/pco∘⍳
      ⍳ ⍝ Generate the range from 1 to the argument
     ∘  ⍝ Compose
  pco   ⍝ P-colon (p:); without a left argument, it generates the first <right_arg> primes.
+/      ⍝ Sum

J. Sallé

Posted 2018-08-07T06:39:43.270

Reputation: 3 233

Don't you have to add yet another byte? import X (newline) X.something() in python is counted with the newline. – Zacharý – 2018-08-14T22:06:34.863

1

Ruby, 22 + 7 = 29 bytes

Run with ruby -rprime (+7)

->n{Prime.take(n).sum}

Piccolo

Posted 2018-08-07T06:39:43.270

Reputation: 261

1

Pari/GP, 20 bytes

n->vecsum(primes(n))

Try it online!

alephalpha

Posted 2018-08-07T06:39:43.270

Reputation: 23 988

1

JAEL, 5 bytes

#&kȦ

Explanation (generated automatically):

./jael --explain '#&kȦ'
ORIGINAL CODE:  #&kȦ

EXPANDING EXPLANATION:
Ȧ => .a!

EXPANDED CODE:  #&k.a!,

#     ,                 repeat (p1) times:
 &                              push number of iterations of this loop
  k                             push nth prime
   .                            push the value under the tape head
    a                           push p1 + p2
     !                          write p1 to the tape head
       ␄                print machine state

Eduardo Hoefel

Posted 2018-08-07T06:39:43.270

Reputation: 587

0

Python 2, 63 59 56 51 bytes

f=lambda n:n and prime(n)+f(n-1)
from sympy import*

Try it online!


Saved:

  • -5 bytes, thanks to Jonathan Allan

Without libs:

Python 2, 83 bytes

n,s=input(),0
x=2
while n:
 if all(x%i for i in range(2,x)):n-=1;s+=x
 x+=1
print s

Try it online!

TFeld

Posted 2018-08-07T06:39:43.270

Reputation: 19 246

f=lambda n:n and prime(n)+f(n-1) saves five (it might be golfable further too) – Jonathan Allan – 2018-08-07T07:24:31.923

0

Pyke, 4 bytes

~p>s

Try it here!

~p   -   prime_numbers
  >  -  first_n(^, input)
   s - sum(^)

Blue

Posted 2018-08-07T06:39:43.270

Reputation: 26 661

0

CJam, 21 bytes

0{{T1+:Tmp!}gT}li*]:+


Explanation:
0{{T1+:Tmp!}gT}li*]:+ Original code

 {            }li*    Repeat n times
  {        }          Block
   T                  Get variable T | stack: T
    1+                Add one | Stack: T+1 
      :T              Store in variable T | Stack: T+1
        mp!           Is T not prime?     | Stack: !(isprime(T))
            g         Do while condition at top of stack is true, pop condition
             T        Push T onto the stack | Stack: Primes so far
0                 ]   Make everything on stack into an array, starting with 0 (to not throw error if n = 0)| Stack: array with 0 and all primes up to n
                   :+ Add everything in array

Try it online!

lolad

Posted 2018-08-07T06:39:43.270

Reputation: 754

0

F#, 111 bytes

let f n=Seq.initInfinite id|>Seq.filter(fun p->p>1&&Seq.exists(fun x->p%x=0){2..p-1}|>not)|>Seq.take n|>Seq.sum

Try it online!

Seq.initInfinite creates an infinitely-long sequence with a generator function which takes, as a parameter, the item index. In this case the generator function is just the identity function id.

Seq.filter selects only the numbers created by the infinite sequence that are prime.

Seq.take takes the first n elements in that sequence.

And finally, Seq.sum sums them up.

Ciaran_McCarthy

Posted 2018-08-07T06:39:43.270

Reputation: 689

0

cQuents, 3 bytes

;pz

Try it online!

Explanation

;    sum of first n terms for input n
 pz  each term is the next prime after the previous term

Stephen

Posted 2018-08-07T06:39:43.270

Reputation: 12 293

Note current version uses Z instead of z – Stephen – 2019-02-01T04:50:20.567

0

MY, 4 bytes

⎕ṀΣ↵

Try it online!

Still regretting no implicit input/output in this garbage language, would've been two bytes otherwise.

  • = input
  • = 1st ... nth prime inclusive
  • Σ = sum
  • = output

Zacharý

Posted 2018-08-07T06:39:43.270

Reputation: 5 710

0

APL(NARS), 27 chars, 54 bytes

{⍵=0:0⋄+/{⍵=1:2⋄¯2π⍵-1}¨⍳⍵}

{¯2π⍵} here would return the n prime different from 2. So {⍵=1:2⋄¯2π⍵-1} would return the n prime 2 in count in it...

RosLuP

Posted 2018-08-07T06:39:43.270

Reputation: 3 036

0

Japt -mx, 8 bytes

T=_j}a°T

Try it

Shaggy

Posted 2018-08-07T06:39:43.270

Reputation: 24 623

0

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.

Wisław

Posted 2018-08-07T06:39:43.270

Reputation: 554

0

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

Sok

Posted 2018-08-07T06:39:43.270

Reputation: 5 592