Sum pyramid of primes
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
Mathematica, 38 36 35 bytes
Prime[r=Range@#].Binomial[#-1,r-1]&
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
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.