Sum pyramid of primes

24

1

Given a number N, the challenge is to get the sum of the pyramid of N primes. To clarify things, here is an example:

Input: 4

We will list the first 4 primes, and then compute the sum of them. After that, we will compute the sums of the sums, and so on:

  2
    > 5
  3     > 13
    > 8      > 33
  5     > 20
    > 12
  7

You can see that the final result is 33. Here is another example, with N = 8:

   2
     >   5
   3       >  13
     >   8       >  33
   5       >  20       >  83
     >  12       >  50       > 205
   7       >  30       > 122       > 495
     >  18       >  72       > 290       > 1169
  11       >  42       > 168       > 674
     >  24       >  96       > 384
  13       >  54       > 216
     >  30       > 120
  17       >  66
     >  36
  19

You can see that the final result is 1169.

Here is another example with an odd N, N = 3:

 2
   > 5
 3     > 13
   > 8
 5

This gives us 13 as the result

Your task is to write a program or a function, that takes an integer greater than 0, and output the final result.

Here are some test results:

1:  2
2:  5
3:  13
4:  33
5:  83
6:  205
7:  495
8:  1169
9:  2707
10: 6169
11: 13889
12: 30993
13: 68701
14: 151469
15: 332349
16: 725837
17: 1577751
18: 3413221
19: 7349029
20: 15751187
21: 33616925
22: 71475193
23: 151466705
24: 320072415
25: 674721797
26: 1419327223
27: 2979993519
28: 6245693407
29: 13068049163
30: 27297614797
31: 56929779663
32: 118543624847
33: 246475746269
34: 511766428817
35: 1061264813321
36: 2198298700845
37: 4548996804811
38: 9405003164065
39: 19429190057417
40: 40107799133677
41: 82736199371081
42: 170553108953473
43: 351333736092089
44: 723224546040181
45: 1487710742395387
46: 3058157261678325
47: 6282142186547177
48: 12896743408107403
49: 26460652594917673
50: 54262186256186881
51: 111224391050741687
52: 227896496141836195
53: 466805185374509003
54: 955904519939662217
55: 1956988697590280537
56: 4005572366722212927
57: 8196803221276230093
58: 16769645303734608963
59: 34300013739423719561
60: 70136585692535099353
61: 143371352962891226373
62: 292978031452308375001
63: 598482012866917021541
64: 1222083126601616763473
65: 2494459637841415902073
66: 5089478703050176444803
67: 10379794709536133386939
68: 21160351440305258275579
69: 43119914481530819445497
70: 87833066190052490228187
71: 178841897161848754603319
72: 364014682565128163812791
73: 740654046243174781813209
74: 1506496270380756958474835
75: 3063280375436290387756263
76: 6227039507615221644290617
77: 12655020557561801933128885
78: 25712267089927372837530869
79: 52230425385198423845305957
80: 106076955379202815098486497
81: 215397386589448754140867649
82: 437308717912632286770415395
83: 887706233370396897803709611
84: 1801721089699452657985592689
85: 3656329898231436156162865559
86: 7418972676822310377574227797
87: 15051599987013574096449515927
88: 30532404546282900804722616529
89: 61926565462373271494414919017
90: 125582269494835615524470915169
91: 254631689768733901573206365479
92: 516210444730946464864091626473
93: 1046330617753410129672316234861
94: 2120493010460433691014704829565
95: 4296639990460140795780826898943
96: 8704509990931940668688755806845
97: 17631229933967301681217551193565
98: 35706243541395815998303171050377
99: 72298621492552303967009812018997

This is , so the shortest amount of bytes wins!

Adnan

Posted 2015-12-05T12:17:05.827

Reputation: 41 965

1Is outputting the sum in a one-element list (e.g. [1169] for 8) acceptable? – Mego – 2015-12-05T12:47:09.070

@Mego Yes, as long as it's the final result – Adnan – 2015-12-05T12:59:57.817

Must we support all test-cases up to 99? Many languages (e.g. JavaScript) can't count that high without losing accuracy. – ETHproductions – 2015-12-05T14:07:35.047

1@ETHproductions Only up to 27, which has the highest result lower than 2^32 - 1 (unsigned maximal int value) – Adnan – 2015-12-05T14:13:08.383

Can you give an example of how to combine the terms with an odd N? – GamrCorps – 2015-12-05T15:18:08.000

11http://oeis.org/A007443 – orlp – 2015-12-05T15:24:50.433

@GamrCorps I have added a new example. – Adnan – 2015-12-05T23:45:01.877

Answers

12

J, 15 bytes

p:@i.+/ .*i.!<:

Explanation:

Basically the same as my Mathematica answer.

p:@i.+/ .*i.!<:
          i.!<:    binomial coefficients
p:@i.              first n primes
     +/ .*         dot product

alephalpha

Posted 2015-12-05T12:17:05.827

Reputation: 23 988

10

Mathematica, 38 36 35 bytes

Prime[r=Range@#].Binomial[#-1,r-1]&

alephalpha

Posted 2015-12-05T12:17:05.827

Reputation: 23 988

10

Minkolang 0.14, 17 bytes

n[i3M$i1-i6M*+]N.

Try it here and check all test cases here.

Explanation

n                    Take number from input (N)
 [                   Open for loop that repeats N times
  i                  Loop counter (n)
   3M                Pop n and push nth prime (where 2 is the 0th prime)
     $i1-            Max iterations - 1 (which is N-1)
         i           Loop counter (n)
          6M         Pop n,k and push kCn (binomial)
            *+       Multiply and add
              ]      Close for loop
               N.    Output as number and stop.

I use basically the same algorithm as several of the earlier answers that use binomial coefficients. Whenever you see such a pyramid of numbers being added, Pascal's triangle should be the first thing to come to mind. I don't see that any of the other answers have explained why this works, so I'll do that.

MORE explanation

2
  > [2,3]
3         > [2,3,3,5]
  > [3,5]             > [2,3,3,3,5,5,5,7]
5         > [3,5,5,7]
  > [5,7]
7

As you can see, the primes 2,3,5,7 appear 1,3,3,1 times in the final result. Lemme change the layout a bit.

_ _ _ 7
_ _ 5
_ 3
2

The number of times that the 3 will contribute to the final result is the same as the number of paths from the 3 to the upper-left corner, moving only up and left. Here, there are three such paths for the 3:

_    _    _ _
_    _ _    _
_ 3    3    3

Note that I can reverse the direction without loss of generality. So I want to know how many paths there are from the upper-left corner to each position along the jagged edge. I can count them like so...

1 1 1 1 1 . . .
1 2 3 4
1 3 6
1 4   .
1       .
.         .
.
.

For every number in this triangle, if it is X units from the left and Y units from the top, then the number at that position is

enter image description here

The way I use it, though, X+Y = N is constant and X ranges from 0 to N, which goes along one diagonal. I multiply each coefficient with the corresponding prime number and then add it all up.

See the Wikipedia article on Pascal's triangle for more on this.

El'endia Starman

Posted 2015-12-05T12:17:05.827

Reputation: 14 504

8I find the explaination quite beautiful +1 – Adnan – 2015-12-05T23:47:09.510

7

JavaScript ES7 107

Abusing the fixed limit at 27 - how boring is actually finding the primes.

n=>eval("t=2;for(p=[for(v of'012242424626424662642646842')t-=-v];--n;)p=p.slice(0,n).map((v,i)=>v+p[i+1])")

Test snippet (using array comprehension it will work only in Firefox)

F=n=>eval("t=2;for(p=[for(v of'012242424626424662642646842')t-=-v];--n;)p=p.slice(0,n).map((v,i)=>v+p[i+1])")

// Less golfed

Q=n=>{
  t=2;
  // Note: the golfed version will return the last computed value, that is p if the loop is entered, else t=2
  p=[for(v of '012242424626424662642646842') t-=-v] // build the array of first 27 primes in p
  while(--n) p = p.slice(0,n).map((v,i)=>v+p[i+1])  
  return p
}  

//TEST
console.log=x=>O.innerHTML+=x+'\n'

for(i=1;i<28;i++)console.log(i+' : '+F(i))
<pre id=O></pre>

edc65

Posted 2015-12-05T12:17:05.827

Reputation: 31 086

Is it possible to shorten the code by using regex prime check? – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-12-07T10:07:55.143

6

Pyth, 18 bytes

husM.:G2tQ.f}ZPZQ0

Try it online: Demonstration

Explanation:

husM.:G2tQ.f}ZPZQ0   implicit: Q = input number
          .f    Q0   find the first Q numbers Z >= 0, which satisfy
            }ZPZ        Z appears in the prime factorization of Z
                     this gives the first Q prime numbers
 u      tQ           assign this list to G and repeat the following Q-1 times:
    .:G2               create all subarrays of length 2
  sM                   sum them up and update G
h                    take the first element (=result) and print

Jakube

Posted 2015-12-05T12:17:05.827

Reputation: 21 462

Also 18: s*V.cLtQUQ.f}ZPZQ0 – Sp3000 – 2015-12-05T14:05:46.923

@Sp3000 Oh wow, this is very similar to my answer - but I didn't look at your comment. – orlp – 2015-12-05T15:45:53.623

6

Pyth - 16 15 bytes

Uses reduce and first_n filter.

u+VGtGtQ.f}ZPZQ

Test Suite.

Maltysen

Posted 2015-12-05T12:17:05.827

Reputation: 25 023

5

Pyth, 16 bytes

s*V.cLtQQ.f}ZPZQ

Very simple actually:

s*V          ; Dot product of
  .cLtQQ     ; the binomial coefficients for n
  .f}ZPZQ    ; and the first n prime numbers.

orlp

Posted 2015-12-05T12:17:05.827

Reputation: 37 067

4

Haskell, 74 bytes

import Data.Numbers.Primes
f n=([]:iterate(zipWith(+)=<<tail)primes)!!n!!0

Usage example:

*Main> map f [1..12]
[2,5,13,33,83,205,495,1169,2707,6169,13889,30993]

How it works: repeatedly calculate the neighbor sums of all primes. Take the head of the nth iteration.

[2,3,5,7,11,13,17,19,23,29,...]             -- plain primes (and 1st iteration)
[5,8,12,18,24,30,36,42,52,60,...]           -- 2nd iteration of neighbor sums
[13,20,30,42,54,66,78,94,112,128,...]       -- 3rd iteration
[33,50,72,96,120,144,172,206,240,274,...]
...

As the index operator !! is zero based, I'm prepending an empty list to avoid having to use !!(n-1).

nimi

Posted 2015-12-05T12:17:05.827

Reputation: 34 639

4

Matlab, 76 bytes

Thanks to David for saving a lot of bytes!

n=input('');x=primes(103);
for s=2:n,x=conv(x,[1 1]);end
disp(num2str(x(n)))

Old version, 98 bytes

n=input('');m=1;x=[];while nnz(x)<n
m=m+1;x=primes(m);end
for s=2:n,x=conv(x,[1 1]);end
disp(x(n))

Luis Mendo

Posted 2015-12-05T12:17:05.827

Reputation: 87 464

Making x using x=primes(103); saves some bytes, since you only need to go up to N=27 (and it doesn't matter if x has more entries than you need). conv was a great idea though! – David – 2015-12-07T04:37:21.770

@David Thanks! I hadn't seen the challenge was only up to 27 – Luis Mendo – 2015-12-07T16:09:19.133

3

JavaScript (ES6), 121 bytes

n=>eval(`for(p=[],c=0,x=1;c<n;s?p[c++]=x:0)for(s=i=++x;--i>1;)x%i?0:s=0;for(;--c;p=s)for(i=c,s=[];i;)s[c-i]=p[i]+p[--i]`)

Explanation

Most of the size comes from finding the prime numbers.

n=>
  eval(`                   // eval used to enable for loops without {} or return

    // Get primes up to n
    for(                   // loop from range 2 to n
      p=[],                // p = primes
      c=0,                 // c = count of primes
      x=1;                 // x = current number to check for primality
      c<n;
      s?p[c++]=x:0         // add the number to the primes if it has no divisors
    )
      for(                 // loop from range 2 to x to check for divisors
        s=                 // s = true if x is a prime
          i=++x;
        --i>1;
      )
        x%i?0:s=0;         // check if x has a divisor

    // Sum primes
    for(;--c;p=s)          // while the new pyramid has pairs to sum
      for(i=c,s=[];i;)     // loop through each pair of the pyramid
        s[c-i]=p[i]+p[--i] // push the sum of the pair to the new pyramid s
  `)                       // implicit: return the final sum

Test

<input type="number" id="input" value="0" oninput="result.textContent=(

n=>eval(`for(p=[],c=0,x=1;c<n;s?p[c++]=x:0)for(s=i=++x;--i>1;)x%i?0:s=0;for(;--c;p=s)for(i=c,s=[];i;)s[c-i]=p[i]+p[--i]`)

)(+this.value)" />
<pre id="result"></pre>

user81655

Posted 2015-12-05T12:17:05.827

Reputation: 10 181

3

Shell + GNU and BSD utilities, 92

echo `primes 1|sed $1q`|sed -r ':
s/(\w+) (\w+)/$((\1+\2)) \2/
t
s/ \w+$//
s/^/echo /e
/ /b'

Digital Trauma

Posted 2015-12-05T12:17:05.827

Reputation: 64 644

2

Seriously, 23 bytes

,r`P`M;lD`;pX@dXZ'Σ£M`n

Outputs the result as a list of length 1: 8 -> [1169]

Try it online

Explanation:

,r`P`M    push the first n primes as a list
;lD       push 1 minus the length of the list (we'll call this k) ([2,3,5,7],3)
`...`n    call the following function k times:
    ;pX      duplicate the list, pop and discard the first element
    @dX      swap, pop and discard the last element
    Z        zip the two lists
    'Σ£      push the string "Σ" and convert to function
    M        map the function over the list

Mego

Posted 2015-12-05T12:17:05.827

Reputation: 32 998

2

Mathematica 73 bytes

NestWhile[Plus@@@Partition[#,2,1]&,Prime@n~Table~{n,#},Length@#>1&][[1]]&

How it works

Prime@n~Table~{n,#}& gives a list of the first # primes.

Partition[#,2,1]& rearranges a list of numbers, {a, b, c, d ...} as {{a,b}, {b,c}, {c,d}...}}.

Plus@@@ then returns {a+b, b+c, c+d...}.

NestWhile begins with the list of # primes and repeatedly applies Plus@@@Partition... as long as there is more than one number in the list.


NestWhile[Plus@@@Partition[#,2,1]&,Prime@n~Table~{n,#},Length@#>1&][[1]]&[4]

33


NestWhile[Plus @@@ Partition[#, 2, 1] &, Prime@n~Table~{n, #}, Length@# > 1 &][[1]] &[5]

83


It takes about 1/5 sec to solve for the first 1000 primes.

NestWhile[Plus @@@ Partition[#, 2, 1] &, Prime@n~Table~{n, #}, 
 Length@# > 1 &][[1]] &[10^3] // AbsoluteTiming

{0.185611, 1917231113909474354152581359443368948301825453723617274940459548079399 7849439430405641625002631859205971635284844253657654843025188471660669 0868945436580032828177831204066809442374364181056590286849530757875874 9185665854180901580438781223737728559484382552514103542932932981340942 3918431043908415228663677}

DavidC

Posted 2015-12-05T12:17:05.827

Reputation: 24 524

1

Jelly, 7 bytes

ÆN€+ƝƬṀ

Try it online!

Originally I wrote a Brachylog answer, 1<|~lṗᵐ≠≜{s₂ᶠ+ᵐ}ⁱ~g, but when it came out to 19 bytes I decided that I should probably try a different language.

      Ṁ    The largest value from
     Ƭ     every stage of repeatedly
   +       adding
    Ɲ      adjacent values, starting with
ÆN         nth prime
  €        mapped over the input.

Apparently, mapping over a number treats it as a range from 1 to itself inclusive, and integers sort as greater than lists or whatever '' is.

Unrelated String

Posted 2015-12-05T12:17:05.827

Reputation: 5 300

1

APL(NARS), 41 chars, 82 bytes

{1=≢⍵:↑⍵⋄∇+/¨¯1↓⍵,¨1⌽⍵}∘{⍵↑v/⍨0πv←⍳1+⍵×⍵}

In input if one want to use big number has to enter the type number_x as 47x. There could be something not ok: i here write that n primes are in the set 1..n^2 Test:

  h←{1=≢⍵:↑⍵⋄∇+/¨¯1↓⍵,¨1⌽⍵}∘{⍵↑v/⍨0πv←⍳1+⍵×⍵}
  h 1
2
  h 2
5
  h 9
2707
  h 24
320072415
  h 47x
6282142186547177 
  h 99x
72298621492552303967009812018997 
  h 200x
433205808657246411262213593770934980590715995899633306941417373

RosLuP

Posted 2015-12-05T12:17:05.827

Reputation: 3 036

1

Perl 6, 52 bytes

{grep(&is-prime,1..*)[^$_],{[|$_]Z+.skip}...1& &say}

Try it online!

Anonymous code block that takes an argument and prints out a one element list containing the result.

Jo King

Posted 2015-12-05T12:17:05.827

Reputation: 38 234

1

Python 2, 159 bytes

m=int(input())
q=[]
x=2
while len(q)<m:
 if not any([x%g<1 for g in q]):q+=[x]
 x+=1
for i in range(m-1):
 for p in q:q+=[q[1]+q[0]];q.pop(0)
 print(q.pop())
print q

Tim

Posted 2015-12-05T12:17:05.827

Reputation: 2 789

1Maybe I'm missing something...but why the print command inside the loop? Don't you want to print just once, at the end? – mathmandan – 2015-12-06T11:29:57.590

1

Ceylon, 169 bytes

alias I=>Integer;I s(I*l)=>l.size<2then(l[0]else 0)else s(*l.paired.map((I[2]i)=>i[0]+i[1]));I p(I n)=>s(*loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(n));

This defines two functions – s calculates the pyramid sum of a sequence of integers, while p calls this on the sequence of the first n primes.

Looks like about half the size is finding the first n primes, other half is calculating the pyramid sum.

Here is a formatted/commented version:

// Sum pyramid of primes
//
// Question:  http://codegolf.stackexchange.com/q/65822/2338
// My answer: http://codegolf.stackexchange.com/a/65879/2338

alias I => Integer;

// Calculate the pyramid sum of some sequence.
I s(I* l) =>
        // If less than two elements ...
        l.size < 2
        // then use the first (only element), or 0 if no such.
        then (l[0] else 0)
        // otherwise,
        else s(*
               // take the iterable of pairs of consecutive elements,
               l.paired
               // and add each of them together.
                .map((I[2] i) => i[0] + i[1])
               // then apply s (recursively) on the result.
               );

// Calculate the pyramid sum of the first n primes.
I p(I n) => s(*
              // the infinite sequence of integers, starting with 2.
              loop(2)(1.plus)
              // filter by primality (using trial division)
              .filter((c) => !(2 : c-2)
                              .any((d) => c%d < 1))
              // then take the first n elements
              .take(n)
              // then apply s on the result.
             );

Paŭlo Ebermann

Posted 2015-12-05T12:17:05.827

Reputation: 1 010

@FlagAsSpam done ... sorry, I somehow forgot that. – Paŭlo Ebermann – 2015-12-07T21:03:29.153

1

Milky Way 1.4.8, 26 25 bytes

This answer is not competing. Some of the operations were created after this question was posted (but not necessarily for this challenge).

'E&{~F§{G}:y1ba?{_^_}};!

I was able to remove a byte after reading through the comments. Output is a single-element list.


Explanation

'                        #  read input from the command line
 E                       #  push a list of the first N primes
  &{~                }   #  while loop
     F                   #  push the sum of TOS elements i.e. [A, B, C] => [[A,B], [B,C]]
      §{ }               #  mapping
        G                #  sum i.e. [1, 2, 3] => 6
          :              #  duplicate the TOS
           y             #  push the length of the TOS to the stack
            1            #  push 1 to the stack
             b           #  evaluate equality of the TOS and STOS
              a          #  logical not
               ?{_ _}    #  if-else statement
                  ^      #  pop the TOS
                     ;   #  swap the TOS and STOS
                         #  dump the TOS to the stack
                      !  #  output the TOS

Usage

python3 milkyway.py <path-to-code> -i <input-integer>

Zach Gates

Posted 2015-12-05T12:17:05.827

Reputation: 6 152

0

Stax, 13 bytes

ä/($◘é∟o¶Vƒm^

Run and debug it

recursive

Posted 2015-12-05T12:17:05.827

Reputation: 8 616