数が連続する素数の合計であるウェイの数


15

1より大きい整数を指定すると、1つ以上の連続する素数の合計として表現できるウェイの数を出力します。

被加数の順序は関係ありません。合計は単一の数値で構成できます(したがって、素数の出力は少なくとも1になります)。

これはです。標準ルールが適用されます。

シーケンス自体OEIS A054845を含む関連情報およびシーケンスについては、このOEIS wikiを参照してください。

テストケース

2 => 1
3 => 1
4 => 0
5 => 2
6 => 0
7 => 1
8 => 1
10 => 1
36 => 2
41 => 3
42 => 1
43 => 1
44 => 0
311 => 5
1151 => 4
34421 => 6

回答:


9

ゼリー 6  5 バイト

-1 Dylnanに感謝

ÆRẆ§ċ

モナドリンク

オンラインでお試しください!または、テストスイートを参照してください(最終テストケースがTIOで60秒でタイムアウトすることに注意してください)。

どうやって?

ÆRẆ§ċ - Link: integer, n
ÆR    - primes from 2 to n inclusive
  Ẇ   - all contiguous substrings
   §  - sum each
    ċ - count occurrences of n

2æRと同じですÆR
ディルナン

@dylnanすてきな方ありがとう!
ジョナサンアラン

8

R、95バイト

function(x,P=2){for(i in 2:x)P=c(P,i[all(i%%P)])
for(i in 1:x){F=F+sum(cumsum(P)==x)
P[i]=0}
F}

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

  • 34421をサポートする私のソリューションにも基本的に革命をもたらした@Giuseppeに-24バイトのおかげです!

1
それは最大までの素数を考える賢い方法xです!
ジュゼッペ


1
@ジュゼッペ:それは素晴らしい!! 今日、私は病気です、そして、私はそれを考えることができなかったでしょう... ll
賛成票

1
@ngm 34421の重要性は?。?そして、@ digEmAll、私は本当に気にしません。連続した素数を取得するcumsumため0に最初のいくつかの要素を使用して設定することについて、私には本当に手がかりがありませんでした。プライムゴルフは、最後のテストケースを機能させようとしているだけで、運がよかったouterです!少なくとも十分な担当者がいるので(少なくとも適切な担当者の要件が得られるまで)、より多くのRゴルファーがより多くの可視性を獲得できるように支援することを常に嬉しく思います!
ジュゼッペ

1
@Giuseppe 34421は、正確に6つの方法で連続する素数の合計である最小数です(oeis.org/A054859を参照)。この課題のために投稿されたほとんどのソリューションは、そのテストケースの時間(TIO上)またはメモリが不足しています。Javaの答えは、シーケンス内の次の整数も取得しましたが(7の場合)、8の場合はそうではありませんでした
。– ngm


4

JavaScript(ES6)、92バイト

n=>(a=[],k=1,g=s=>k>n?0:!s+g(s>0?s-(p=d=>k%--d?p(d):d<2&&a.push(k)&&k)(++k):s+a.shift()))(n)

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

コメント済み

n => (                          // n = input
  a = [],                       // a[] = array holding the list of consecutive primes
  k = 1,                        // k = current number to test
  g = s =>                      // g = recursive function taking s = n - sum(a)
    k > n ?                     //   if k is greater than n:
      0                         //     stop recursion
    :                           //   else:
      !s +                      //     increment the final result if s = 0
      g(                        //     add the result of a recursive call to g():
        s > 0 ?                 //       if s is positive:
          s - (                 //         subtract from s the result of p():
            p = d => k % --d ?  //           p() = recursive helper function looking
              p(d)              //                 for the highest divisor d of k,
            :                   //                 starting with d = k - 1
              d < 2 &&          //           if d is less than 2 (i.e. k is prime):
              a.push(k) &&      //             append k to a[]
              k                 //             and return k (else: return false)
          )(++k)                //         increment k and call p(k)
        :                       //       else:
          s + a.shift()         //         remove the first entry from a[]
                                //         and add it to s
      )                         //     end of recursive call
  )(n)                          // initial call to g() with s = n

4

MATL、15 12バイト

EZqPYTRYsG=z

MATL Onlineでお試しください

初期値E(2で乗算)は、素数入力に対して、後の結果を確実にします。Yscumsum)のに、行列のゼロ部分で繰り返される入力素数がないことを確認します(したがって、カウントを混乱させます)。

説明:

                % Implicit input, say 5
E               % Double the input
 Zq             % Get list of primes upto (and including) that
                %  Stack: [2 3 5 7]
   P            % Reverse that list
    YT          % Toeplitz matrix of that
                %  Stack: [7 5 3 2
                           5 7 5 3
                           3 5 7 5
                           2 3 5 7]
      R         % `triu` - upper triangular portion of matrix
                %  Stack: [7 5 3 2
                           0 7 5 3
                           0 0 7 5
                           0 0 0 7]
       Ys       % Cumulative sum along each column
                %  Stack: [7  5  3  2
                           7 12  8  5
                           7 12 15 10
                           7 12 15 17]


         G=     % Compare against input - 1s where equal, 0s where not
           z    % Count the number of non-zeros

1
素数と三角形部分のテプリッツ行列、とてもいい!
ルイスメンドー

4

Brachylog14 9バイト

{⟦ṗˢs+?}ᶜ

オンラインでお試しください!
複数のテストケース

(@Kroppebのおかげで、全体で5バイト!)

説明:

{⟦ṗˢs+?}ᶜ
{      }ᶜ     Count the number of ways this predicate can succeed:
 ⟦            Range from 0 to input
  ṗˢ          Select only the prime numbers
    s         The list of prime numbers has a substring (contiguous subset)
     +        Whose sum
      ?       Is the input

ループ⟦ṗˢ内で計算することでゴルフをすることができます。この{⟦ṗˢs+;?=}ᶜテストスイートを入手しました:オンラインで試してください!
クロペブ

;?=by ?を置き換えて取得できることに{⟦ṗˢs+?}ᶜ
気づいた

@Kroppebもちろん!それもはるかにエレガントな答えです。ありがとうございました。
スンダ

3

Retina 0.8.2、68バイト

.+
$*_$&$*
_
$`__¶
A`^(__+)\1+$
m)&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1)

オンラインでお試しください!リンクには、より高速なテストケースが含まれています。説明:

m)

どこ複数行モードで全体のスクリプトを実行^し、$すべての行に一致します。

.+
$*_$&$*

最初に_s を使用してからs を使用して、単項式に2回変換し1ます。

_
$`__¶

_2n+1

A`^(__+)\1+$

範囲内のすべての合成数を削除します。

&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1)

__1n


3

9 8バイト

Mr.Xcoderのおかげで-1バイト(の¹代わりに名前付き引数を使用S)!

#¹ṁ∫ṫ↑İp

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

説明

#¹ṁ∫ṫ↑İp  -- example input: 3
#¹        -- count the occurrences of 3 in
      İp  -- | primes: [2,3,5,7..]
     ↑    -- | take 3: [2,3,5]
    ṫ     -- | tails: [[2,3,5],[3,5],[5]]
  ṁ       -- | map and flatten
   ∫      -- | | cumulative sums
          -- | : [2,5,10,3,8,5]
          -- : 1

完全なプログラムとして、#¹ṁ∫ṫ↑İp1バイトを節約する必要があります。
Mr Xcoder

3

MATL、16バイト

:"GZq@:g2&Y+G=vs

MATL Onlineでお試しください!

説明

:"        % Input (implicit): n. For each k in [1 2 ... n]
  G       %   Push n
  Zq      %   Primes up to that
  @:g     %   Push vector of k ones
  2&Y+    %   Convolution, removing the edges
  G=      %   True for entries that equal n
  v       %   Concatenate vertically with previous results
  s       %   Sum
          % End (implicit). Display (implicit)


2

クリーン100 98バイト

import StdEnv,StdLib
$n=sum[1\\z<-inits[i\\i<-[2..n]|all(\j=i/j*j<i)[2..i-1]],s<-tails z|sum s==n]

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

$ :: Int -> Int以下で説明するように機能する関数を定義します。

$ n                              // the function $ of n is
    = sum [                      // the sum of
        1                        // 1, for every 
        \\ z <- inits [          // prefix z of 
            i                    // i, for every
            \\ i <- [2..n]       // integer i between 2 and n
            | and [              // where every
                i/j*j < i        // j does not divide i
                \\ j <- [2..i-1] // for every j between 2 and i-1
            ]
        ]
        , s <- tails z           // ... and suffix s of the prefix z
        | sum s == n             // where the sum of the suffix is equal to n
    ]

(説明は古いが論理的に同一のバージョン用です)


1
34421の出力を取得するための特別な称賛。
ngm18年

2

Perl 6、53バイト

{+grep $_,map {|[\+] $_},[\R,] grep *.is-prime,2..$_}

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

三角形の縮小演算子を2回使用します。最後のテストケースは、TIOには遅すぎます。

説明

{                                                   } # Anonymous block
                               grep *.is-prime,2..$_  # List of primes up to n
                         [\R,]  # All sublists (2) (3 2) (5 3 2) (7 5 3 2) ...
          map {|[\+] $_},  # Partial sums for each, flattened
 +grep $_,  # Count number of occurrences

2

Japt、17バイト

これよりも短い方法があります!

最後のテストケースを除外します。

õ fj x@ZãYÄ x@¶Xx

試してみるかすべてのテストケースを実行してください


説明

                      :Implicit input of integer U
õ                     :Range [1,U]
  fj                  :Filter primes
      @               :Map each integer at 0-based index Y in array Z
         YÄ           :  Y+1
       Zã             :  Subsections of Z of that length
             @        :  Map each array X
               Xx     :    Reduce by addition
              ¶       :    Check for equality with U
            x         :  Reduce by addition
     x                :Reduce by addition

2

Javaの10、195の 194 184 182バイト

n->{var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}for(x=L.size(),i=0;i<x;)for(k=i++,s=0;k<x;r+=s==n?1:0)s+=(int)L.get(k++);return r;}

@ceilingcatのおかげで-1バイト。@SaraJの
おかげで-10バイト。

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

説明:

n->{                // Method with integer as both parameter and return-type
  var L=new java.util.Stack();
                    //  List of primes, starting empty
  int i=1,k,x,s,    //  Temp integers
      r=0;          //  Result-counter, starting at 0
  for(;i++<n;){     //  Loop `i` in the range [2, `n`]
    for(k=1;        //   Set `k` to 1
        i%++k>0;);  //   Inner loop which increases `k` by 1 before every iteration,
                    //   and continues as long as `i` is not divisible by `k`
    if(k==i)        //   If `k` is now still the same as `i`; a.k.a. if `i` is a prime:
      L.add(i);}    //    Add the prime to the List
  for(x=L.size(),   //  Get the amount of primes in the List
      i=0;i<x;)     //  Loop `i` in the range [0, amount_of_primes)
    for(s=0,        //   (Re)set the sum to 0
        k=i++;k<x;  //   Inner loop `k` in the range [`i`, amount_of_primes)
        r+=s==n?    //     After every iteration, if the sum is equal to the input:
            1       //      Increase the result-counter by 1
           :        //     Else:
            0)      //      Leave the result-counter the same by adding 0
      s+=(int)L.get(k++);
                    //    Add the next prime (at index `k`) to the sum
  return r;}        //  And finally return the result-counter

それは、基本的に似てゼリー05AB1E答え、ちょうど190バイト詳細.. XDは
ちょうど楽しみのために追加の部品のそれぞれについて、ここでの比較、(およびJavaはとても冗長である理由を参照し、これらのゴルフ言語はとても強力であるため)。

  1. 入力を受け取ります:(Jelly:0バイト)暗黙的に ; (05AB1E:0バイト)暗黙的に ; (Java 10:5バイト)n->{}
  2. 範囲内の素数のリストを作成します[2, n]:(Jelly:2 bytes)ÆR; (05AB1E:2バイト)ÅP; (Java 10:95バイト)var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}
  3. すべての連続サブリストを取得します:(ゼリー:1バイト); (05AB1E:1バイト)Œ; (Java 10:55バイト)for(x=L.size(),i=0;i<x;)for(k=i++;k<x;)および(int)L.get(k++);
  4. 各サブリストの合計:(ゼリー:1バイト)§; (05AB1E:1バイト)O; (Javaの10:9バイト),s,s=0s+=
  5. 入力に等しいものを数えます:(ゼリー:1バイト)ċ; (05AB1E:2バイト)QO; (Java 10:15バイト),r=0およびr+=s==n?1:0
  6. 結果を出力します:(Jelly:0 bytes)implicitly ; (05AB1E:0バイト)暗黙的に ; (Java 10:9バイト)return r;

1
34421の出力を取得するための特別な称賛。
ngm18年

@ngm :) Javaは多くの点で悪いかもしれませんが、パフォーマンスに関しては通常かなり良いです。
ケビンCruijssen

1
3634531.とアウト218918.タイムズ紙の上でも動作します
NGM

1
@ngm実際には、内部ループ内で繰り返しを218918行うことを考慮して、12.5秒tbhで実行できるほど高速であることには驚いてい218918-2 = 218,916ますn。すべての素数の繰り返し。偶数ごとに1回の反復。そして、[2,p/2)奇数ごとの反復の間(20億回に近い反復)のどこかに、その後19518、メモリ内のリストに素数を追加します。そしてsum([0,19518]) = 190,485,921、2番目のネストされたループでさらに数回ループします。正確には、合計2,223,570,640回の繰り返しです。
ケビンクルーッセン

@ceilingcatありがとう。@SaraJの代替プライムチェックでさらに12バイトをゴルフすることができ%iました。範囲内[2, n]でチェックしているので、トレーリングを引いたので、チェックする必要はありませんi=1。:)
ケビンクルーッセン

1

Physica、41バイト

->x:Count[Sum@Sublists[PrimeQ$$[…x]];x]

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

使い方

->x:Count[Sum@Sublists[PrimeQ$$[…x]];x] // Full program.
->x:            // Define an anonymous function with parameter x.
    […x]        // Range [0 ... x] (inclusive).
        $$      // Filter-keep those that...
  PrimeQ        // Are prime.
 Sublists[...]  // Get all their sublists.
Sum@            // Then sum each sublist.
Count[...;x]    // Count the number of times x occurs in the result.

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