素数の和ピラミッド


24

数Nが与えられると、N個の素数のピラミッドの合計を取得することが課題になります。物事を明確にするために、以下に例を示します。

Input: 4

最初の4素数をリストし、それらの合計を計算します。その後、合計の合計を計算します。

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

最終結果は33であることがわかります。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

最終結果は1169であることがわかります。

奇数N、N = 3の別の例を次に示します。

 2
   > 5
 3     > 13
   > 8
 5

これにより、結果として13が得られます。

あなたの仕事は、0より大きい整数を取るプログラムまたは関数を作成し、最終結果を出力することです。

テスト結果は次のとおりです。

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

これはなので、最短のバイト数が勝ちです!


1
1要素のリストで合計を出力している(例えば[1169]のために8許容可能な)?
Mego

@Megoはい、最終結果である限り
Adnan

99までのすべてのテストケースをサポートする必要がありますか?多くの言語(JavaScriptなど)は、精度を損なうことなくその高さを数えることができません。
ETHproductions

1
@ETHproductions最大27までで、2 ^ 32-1(符号なしの最大int値)未満の最高の結果が得られます
Adnan

回答:




10

Minkolang 0.14、17バイト

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

ここ試してすべてのテストケースをここで確認してください

説明

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.

基本的に、二項係数を使用する以前の回答のいくつかと同じアルゴリズムを使用します。このような数字のピラミッドが追加されるのを見るたびに、Pascalの三角形が最初に頭に浮かぶはずです。他の答えのどれもがなぜこれが機能するのかを説明していないので、私はそうします。

詳細説明

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

ご覧のように、素数は最終結果の時間に2,3,5,7表示さ1,3,3,1れます。Lemmeはレイアウトを少し変更します。

_ _ _ 7
_ _ 5
_ 3
2

回数3最終結果に寄与するであろうからパスの数と同じであり3、左上隅にのみ起動し、左側の移動します。ここでは、次のような3つのパスがあり3ます。

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

一般性を失うことなく方向を反転できることに注意してください。したがって、左上隅からギザギザのエッジに沿った各位置までのパスの数を知りたいです。そのように数えることができます...

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

この三角形のすべての数値について、左からXユニット、上からYユニットの場合、その位置の数値は

ここに画像の説明を入力してください

ただし、私が使用する方法X+Y = Nは一定で、X範囲は0からNであり、1つの対角線に沿っています。各係数に対応する素数を乗算し、すべて加算します。

詳細については、パスカルの三角形に関するウィキペディアの記事を参照してください。


8
私は説明が非常に美しいと思う+1
アドナン

7

JavaScript ES7 107

27の固定制限を乱用する-退屈が実際に素数を見つける方法。

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])")

テストスニペット(配列内包表記を使用すると、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>


正規表現の素数チェックを使用してコードを短縮することは可能ですか?
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

6

Pyth、18バイト

husM.:G2tQ.f}ZPZQ0

オンラインで試す:デモンストレーション

説明:

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

また18:s*V.cLtQUQ.f}ZPZQ0
Sp3000

@ Sp3000うわー、これは私の答えに非常に似ています-しかし、私はあなたのコメントを見ませんでした。
orlp


5

Pyth、16バイト

s*V.cLtQQ.f}ZPZQ

実際には非常に簡単です:

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

4

Haskell、74バイト

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

使用例:

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

仕組み:すべての素数の隣接和を繰り返し計算します。n番目の反復の先頭を取ります。

[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,...]
...

インデックス演算子!!はゼロベースなので、を使用する必要がないように空のリストを先頭に追加しています!!(n-1)


4

Matlab、76バイト

たくさんのバイトを節約してくれたDavidに感謝します!

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

古いバージョン、98バイト

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))

x使用することでx=primes(103);いくつかのバイトを節約できます。必要なのは、必要以上のエントリがあるN=27かどうかxだけです。convでも素晴らしいアイデアでした!
デビッド

@Davidありがとう!私はチャレンジが27までしかなかったことを見ていませんでした
ルイスメンドー

3

JavaScript(ES6)、121バイト

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]`)

説明

サイズのほとんどは、素数を見つけることから来ています。

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

テスト


3

シェル+ GNUおよびBSDユーティリティ、92

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

2

真剣に、23バイト

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

結果を長さ1のリストとして出力します。 8 -> [1169]

オンラインで試す

説明:

,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

2

Mathematica 73バイト

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

使い方

Prime@n~Table~{n,#}& 最初のリストを与える #素数の。

Partition[#,2,1]&、番号のリストを並べ替え{a, b, c, d ...}など {{a,b}, {b,c}, {c,d}...}}

Plus@@@ その後戻ります {a+b, b+c, c+d...}

NestWhile#素数のリストから始まり、リストにPlus@@@Partition...複数の数字がある限り繰り返し適用されます。


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


最初の1000個の素数を解くには約1/5秒かかります。

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

{0.185611、1917231113909474354152581359443368948301825453723617274940459548079399 7849439430405641625002631859205971635284844253657654843025188471660669 086894543658003282817783120406680944237436418105659028684953075787587493918441041025107727722931049185191065658541809015804387812237377285594843825525510109810


1

Python 2、159バイト

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

1
たぶん私は何かを見逃しています...しかし、なぜprintループ内のコマンドですか?最後に一度だけ印刷したくないですか?
mathmandan

1

天の川1.4.826の 25バイト

この答えは競合していません。一部の操作は、この質問が投稿された後に作成されました(ただし、必ずしもこの課題のためではありません)。

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

コメントを読んだ後、1​​バイトを削除できました。出力は単一要素のリストです。


説明

'                        #  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

使用法

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

1

セイロン、169バイト

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));

これは2つの関数を定義します– s整数のシーケンスのピラミッド和を計算pしますが、最初のn素数のシーケンスでこれを呼び出します。

約半分のサイズが最初のサイズを見つけているようです n素数を、他の半分はピラミッドの合計を計算しています。

フォーマット済み/コメント付きのバージョンは次のとおりです。

// 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.
             );

@FlagAsSpam完了...すみません、どういうわけか忘れました。
パエロエベルマン

1

ゼリー、7バイト

ÆN€+ƝƬṀ

オンラインでお試しください!

もともとBrachylogの回答を書きました1<|~lṗᵐ≠≜{s₂ᶠ+ᵐ}ⁱ~gが、19バイトになったときに、おそらく別の言語を試してみることにしました。

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

どうやら、数値をマッピングすると、それは1からそれ自体までの範囲として扱われ、整数はリストまたはその他のものよりも大きいものとしてソートされます''


1

APL(NARS)、41文字、82バイト

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

入力で大きな数字を使用したい場合は、タイプnumber_xを47xとして入力する必要があります。うまくいかない可能性があります:ここでは、n個の素数がセット1..n ^ 2にあると書いています。テスト:

  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


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.