+1素数のカウント


25

自然数のように定義pがある+1素数自然数のN場合、pは素数と標準バイナリ表現である(すなわち、先頭のゼロなし)P(すなわち、前置、付加又は挿入)を添加することによって得ることができます単一の1からnの標準バイナリ表現。

たとえば、17のバイナリ表現は10001 2です。添加することにより形成することができる別個の自然数110001 2がある110001 2または49101001 2または41100101 2または37、および100011 2または35

これらのうち、4137は素数であるため、17には2つの+1素数があります。

仕事

厳密に正の整数受け入れプログラムまたは機能書き込みN入力及び印刷またはリターンとして別個の数+1素数Nを

入力と出力は、整数か、その10進数または単項文字列表現でなければなりません。

標準の規則が適用されます。

テストケース

Input:  4
Output: 0

Input:  1
Output: 1

Input:  17
Output: 2

Input:  33
Output: 3

Input:  553
Output: 4

Input:  3273
Output: 5

Input:  4145
Output: 6

Input:  4109
Output: 7

Input:  196869
Output: 8

1
クール!今夜時間があれば、今すぐ答えます
-anOKsquirrel

回答:


5

Pyth、20バイト

s/LPd{mij\1c.BQ]d2hQ

テストスイート

s/LPd{mij\1c.BQ]d2hQ
                        Q = eval(input())
      m           hQ    For insertion position in [0 ... Q]
            .BQ         Convert Q to binary string
           c   ]d       Chop at insertion position
        j\1             Join on '1'
       i         2      Convert to integer
     {                  Deduplicate
 /LPd                   Map each number to the number of times it occurs in its
                        prime factorization, e.g. whether or not it is prime.
s                       Sum and print.

1
「重複排除」は実際には単語です。
リルトシアスト

8

JavaScript ES6、141バイト143 147 160

@Naouakのおかげで13バイト節約

n=>[...t=n.toString(2)].map((l,i)=>t.slice(0,v=i+1)+1+t.slice(v)).filter((l,i,a)=>a.indexOf(l)==i&&(p=(n,c)=>n%c&&c>n-2||p(n,++c))('0b'+l,2))

TeaScriptの答えと同じ方法で、素数をチェックするためにRegExp(あなたは私が正しいと聞いた)を使用します。

非ゴルフ

n=>
   [...t = n.toString(2)]                  // To binary
   .map((l,i)=>                            // Make cycles
               t.slice(0, v = i+1)
               + 1
               + t.slice(v)
   ).filter((l,i,a)=>  
                     a.indexOf(l) == i &&  // Remove Duplicates
                     (p=(n,c)=>            // Prime checking
                               n % c &&
                                 c > n - 2 ||
                                 p(n,++c)
                     )('0b'+l,2)
   ).length

次のような素数をチェックするビットを短くできると思います:(p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0)('0b'+l,2)代わりに!Array(+('0b'+l)+1).join(1).match(/^1?$|^(11+?)\1+$/)
-Naouak

@Naouak Awesomeは13バイトを節約します!:)
ダウンゴート

4

Minkolang 0.1154の 52バイト

n1(2*d0c`,)(0c1c$%$r2*1c*1c++1g2:d1G)rxSI1-[0g2M+]N.

説明

n             Get integer from input (let's call it n)
1(       )    Get the smallest power of 2 (say, k) greater than input (starting with 1)
  2*d         Multiply by 2 and duplicate
     0c`,     Copy n and see if it's greater (while loop breaks on 0)

(0c1c$%                       Copy n, copy k, and divmod (pushes n//k, n%k)
       $r                     Swap top two elements
         2*                   Multiply by 2
           1c*                Copy k and multiply
              1c+             Copy k and add
                 +            Add
                  1g2:        Get k and divide by 2
                      d1G)    Duplicate and put one copy back in its former place

rx            Reverse and dump (dumps n and top of stack is now 0)
S             Remove duplicates
I1-[     ]    Check each element for primality
    0g        Get potential prime from bottom of stack
      2M      1 if prime, 0 otherwise
        +     Add (this is why I didn't dump the left-over 0 earlier)
N.            Output as integer and stop.

Minkolangの別のバージョンを言うのはいつも楽しみです。
コナーオブライエン

4

TeaScript、22 バイト

x÷¿®x÷E(i¬,1)¤©d¡F(¥)n

TeaScriptはAPLのように見え始めています...特殊文字は、より長く一般的に繰り返されるシーケンスに変換されます

オンライン通訳者は、必ず「入力は数字です」を確認してください。

説明&& Ungolfed

xT(2)s``m(#P(xT(2)E(i+1,1),2))d()F($P)n

xT(2)      // Take input, convert to binary
s``m(#     // Loop over input

  P(         // Convert to decimal...
     xT(2)     // Input to binary
     E(i+1,1)  // Inset 1 into (above) at current index in loop
  ,2)    

)d()       // Remove duplicates
F($P)      // Filter items that aren't prime
n          // Grab length.

これは、Xubuntuの上のgeditを使用して、方法によって、31のバイトだ
グレンO

1
UTF-8エンコードでは31バイトですが、ISO-8859-1では22バイトです。
デニス

4

ジュリア、55 52バイト

n->sum(isprime,∪(2n+(k=2.^(0:endof(bin(n))))-n%k))

k=2.^(0:endof(bin(n)))1から2のべき乗を含む配列を生成しnます。2n+k-n%k次に、配列演算を使用して、考えられるすべての「+1番号」を決定します。(この状況unionと同じことを行うに相当unique)は、繰り返し値を削除します。次にsum(isprime,)、リスト上の素数の数を数えます。


4

CJam、26バイト

勝者ではありませんが、既存のCJamの回答を非常にしっかりと上回っており、0.6.5コマンドを使用するのは初めてe\です。

1ri2b+_,{_)e\_}%_&{2bmp},,

ここでテストしてください。

説明

1       e# Push a 1 (this is the 1 we'll be inserting everywhere).
ri      e# Read input and convert to integer.
2b      e# Convert to base 2.
+       e# Prepend the 1.
_,      e# Duplicate and get the number of bits N.
{       e# Map this block over i from 0 to N-1...
  _)    e#   Create a copy and increment to i+1.
  e\    e#   Swap the bits at positions i and i+1, moving the 1 one step through the array.
  _     e#   Duplicate so we keep this version on the stack.
}%
_&      e# Remove duplicates via set intersection with itself.
{       e# Filter the remaining digit lists based on this block...
  2b    e#   Convert bits back to an integer.
  mp    e#   Test for primality.
},
,       e# Get the length of the remaining list.

注目に値するものの1つは、最初のコピーを作成する前01前にビットを交換するため、1先頭にプリペンドされた元の配列が失われることです。ただし、入力は常に正であるため、先頭の数字は常に1になります。つまり、別のリストを追加した後、数字リストは常に先頭にある[1 1 ...]ため、最初のスワップはどのような場合でもノーオペレーションになります。


3

Mathematica、87バイト

Union[#~FromDigits~2&/@StringReplaceList[#~IntegerString~2,a_:>a<>"1"]]~Count~_?PrimeQ&

3

ジュリア、110の 108 104 87バイト

n->sum(i->isprime(parse(Int,i,2)),(b=bin(n);∪([b[[1:i;1;i+1:end]]for i=1:endof(b)])))

これにより、整数を受け入れて整数を返す名前のない関数が作成されます。呼び出すには、名前を付けf=n->...ます。

ゴルフをしていない:

function f(n::Integer)
    # Get the binary representation of n as a string
    b = bin(n)

    # Construct an array consisting of binary strings with
    # a one prepended, appended, and each insertion
    x = [b[[1:i; 1; i+1:end]] for i = 1:endof(b)]

    # Count the number of primes
    c = sum(i -> isprime(parse(Int, i, 2)), unique(x))

    return c
end

グレンOのおかげで17バイトを節約しました!


binは1から開始する必要があるため、を個別に処理する必要はありません"1"b。そしての場合i=length(b)、にb[i+1:end]相当する""ので、そのエントリは必要ありません(b=bin(n)ある時点で処理する必要があります)。また、2バイト少ない場合sumと同じことをcount行います。
グレンO

また、bとにかく長さの範囲を使用するので、ちょっとしたトリックでそれを取得することもできます- b=bin(n)[s=1:end]そしてfor i=s理解のために。
グレンO

また、最初のビットをbin1にする必要があるという事実を使用して、別のバイトを保存することもできn->sum(i->isprime(parse(Int,i,2)),(b=bin(n);unique([b[[1:i;1;i+1:end]]for i=1:endof(b)])))ます。これにより、カウントが90バイトになります。
グレンO

実際には、交換することにより、1つのより多くのバイトを脱いuniqueunion-入力として一つだけ配列を指定した場合には、同じことを行います。または、さらに良い、代わりにunion
グレンO

@GlenOあなたはマスターです。先生、ありがとう!
アレックスA.

2

CJam、58バイト

L{:TQ\=A+Q\+TWe\-2<s:~2b}q~2b0+:Q,(%{:BLe=!{B+:L}&}%~:mp:+

これには1日かかりましたが、これが4回目の繰り返しでした。



1

PHP、145バイト

読みやすくするために改行を追加しました。

function($n){for($b=base_convert;++$i<=strlen($s=$b($n,10,2));$r+=!$s[$i]&$k<=$j)
for($j=1;($k=$b(substr_replace($s,1,$i,0),2,10))%++$j;);echo$r;}


1

APL、55

{+/{2=+/0=⍵|⍨⍳⍵}¨∪⍵{2⊥(⍵↑X),1,⍵↓X←⍺⊤⍨N⍴2}¨-1-⍳N←1+⌊2⍟⍵}

2バイト短いDyalog固有のバージョン:

{+/2=+/¨0=|⍨∘⍳⍨¨∪⍵{2⊥⍵(↑,(1∘,↓))⍺⊤⍨N⍴2}¨-1-⍳N←1+⌊2⍟⍵}

1

Matlab(120)

n=input('');a=dec2bin(n);g=arrayfun(@(x)bin2dec(cat(2,a(1:x),49,a(x+1:end))),1:log2(n));nnz(unique(g(find(isprime(g)))))

  • 進行中のさらなるゴルフ...

1

Brachylog、17バイト

{ḃ~c₂{,1}ʰc~ḃṗ}ᶜ¹

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

入力変数を介して入力し、出力変数を介して出力します。

{             }ᶜ¹    Count every unique
             ṗ       prime number
           ~ḃ        the binary representation of which is
 ḃ                   the binary representation of the input
  ~c₂                partitioned into two (possibly empty) lists
     {  }ʰ           with the first list
      ,1             having a 1 appended
          c          and the two lists then being concatenated back into one.


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