プライムスクエアを作ろう!


17

プライムスクエアとは何ですか?

プライムスクエアは、4つのエッジすべてが異なる素数であるスクエアです。
しかし、どれですか?
そして、それらをどのように構築しますか?

4x4プライムスクエアの例を次に示します

1009  
0  0     
3  0   
1021    

まず、左上隅から始めます。時計回りに作業しています1009の数字を
持つ最小の素数を選択します。 4

次に4、で始まる数字を持つ最小の素数が必要9です。これは9001です

3番目(4桁)の素数は1、最後の桁(9001がで終わるため1
である必要があり、かつエッジとして以前に使用されいないこのプロパティを持つ最小の4桁の素数である必要があります
この素数は1021です

第四の素数が持っている必要があり4、数字を開始する1(なぜなら1009ので始まる1)と1(なぜなら1021ので始まる1
このプロパティを持つ最小の4桁の素数エッジは以前のように使用されていないです1031

あなたのタスク

あなたは、整数与えられますnから3 to 100
の寸法になります。この番号をn x n四角
次に必要があり、正確に次のテストケースの形式で出力この広場

テストケース

n=3  
Output    

101
3 0
113     

n=5    
Output     

10007
0   0
0   0    
9   0    
10061     

n=7     
Output    

1000003    
0     0     
0     0     
0     0     
0     0     
8     1     
1000037      

n=10      
Output     

1000000007      
0        0      
0        0     
0        0      
0        0       
0        0       
0        0      
1        0      
8        0       
1000000021      

n=20       
Output     

10000000000000000051     
0                  0          
0                  0           
0                  0           
0                  0          
0                  0           
0                  0          
0                  0           
0                  0           
0                  0          
0                  0          
0                  0          
0                  0           
0                  0           
0                  0          
0                  0            
0                  0          
0                  0              
9                  8      
10000000000000000097
  • 入力と出力は、任意の便利な方法で指定できます。
  • STDOUTに出力するか、関数の結果として返すことができます。
  • 完全なプログラムまたは機能のいずれかが受け入れられます。
  • 数字が適切に並んでいる限り、任意の量の無関係な空白を使用できます
  • 標準的な抜け穴は禁止されています。
  • これはので、通常のゴルフルールがすべて適用され、最短のコード(バイト単位)が勝ちます。

編集
これはすべての人に可能n
ですn=100

1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000289        
9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000091            
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000711             
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002191     



そして、これが可能だとは思わないあなたのために、ここにはすべてのテストケースがあります


nは100まで行くことができるならば、いくつかの大きなテストケースを持っているのは良いかもしれません10 = nより
gastropner

4
すべてのn:P でこれが可能であることを証明できますか?チャレンジの問題ではなく、好奇心だけです。
マジックタコUr

2
@MagicOctopusUrnそれは間違いなくすべてnに対して不可能です:n= 1の場合、4つのエッジが異なる素数であるという制約を満たすことができませんが、n= 2の場合、11,13,23を選択するように強制され、その時点で最終エッジ12コンポジットです。n2を超えるすべての可能性があるという証拠はありませんが、そうでなければ学習することにショックを受けます。非公式には、桁数が多いほど、制約を満たすための「小刻みの部屋」が増えます。
ダニエルワグナー

@DanielWagnerとの比率の多くの上限は長年にわたって証明されており、バートランドの仮説を大幅に改善しています。ここで与えられ式は、これがことを証明するのに十分なはず。 P K K 463 N 4pk+1pkk463n4
アーナウド

2
@MagicOctopusUrn 算術級数の素数定理は、 1、3、7 、および9で終わる素数の密度についてかなり強いことを示しています(表記では、n = 10、a = 1/3/7/9を取ります)。十分に大きいn場合n、1で始まり各桁で終わる長さの素数が少なくとも2つあり(したがって、下端を選択できます)、1で始まり1で終わる少なくとも3つの素数があります(したがって、左端)。
ダニエルワグナー

回答:


4

05AB1E64 63 56 53 48 46 バイト

°ÅPIùćÐ4FˆθUKD.ΔθyXÅ?yXÅ¿)¯gè}ÐNĀiR}¦}I¯JŽ9¦SΛ

-1バイトは感謝@ Mr.Xcoder
へ-5バイトおかげ@Grimy

オンラインでお試しください。(タイムアウトになります。ここでは、タイムアウトするわずかに高速な53バイトバージョンです。)n>4n > 7n>7

説明:

°                 # Raise the (implicit) input to the power 10
 ÅP               # Get a list of primes within the range [2, n^10]
   Iù             # Only keep those of a length equal to the input
ć                 # Extract the head; push the remainder-list and first prime separately
 Ð                # Triplicate this first prime
4F                # Loop 4 times:
  ˆ               #  Add the (modified) prime at the top of the stack to the global array
  θU              #  Pop and store the last digit of the prime in variable `X`
  K               #  Remove this prime from the prime-list
  D               #  Duplicate the prime-list
                #  Find the first prime `y` in the prime list which is truthy for:
     θ            #   Get the last digit of prime `y`
     yXÅ?         #   Check if prime `y` starts with variable `X`
     yXÅ¿         #   Check if prime `y` ends with variable `X`
     )            #   Wrap the three results above into a list
      ¯g          #   Get the amount of items in the global array
        è         #   And use it to index into these three checks
                  #   (Note that only 1 is truthy for 05AB1E, so the `θ` basically checks
                  #    if the last digit of prime `y` is 1)
                #  Triplicate the found prime
      NĀi }       #  If the loop index is 1, 2, or 3:
         R        #   Reverse the found prime
      ¦           #  And then remove the first digit of the (potentially reversed) prime
}                 # After the loop:
 I                # Push the input as length
 ¯J               # Push the global array joined together to a single string
 Ž9¦S             # Push compressed integer 2460 converted to a list of digits: [2,4,6,0]
 Λ                # Draw the joined string in the directions [2,4,6,0] (aka [→,↓,←,↑])
                  # of a length equal to the input
                  # (which is output immediately and implicitly as result)

理由を理解するにŽ9¦、この05AB1Eのヒント(大きな整数を圧縮する方法?参照してください2460。また、この05AB1Eのヒントを参照して、Canvasビルトインで正方形がどのように出力されるかを理解してΛください。

広場にキャンバスを印刷するための関連するコードは次のようになりますNĀiR}¦I¯JŽ9¦SΛn=4例としてみましょう。残りのコードで見つかる素数は[1009,9001,1021,1031]です。この段落で説明した最初のコード部分は、代わりに次のように保存します[1009,"001","201","301"]。この段落の第2のコード部分は、その後、組み込みキャンバスを使用するΛオプションを有する:
- (サイド長さ)= :入力 -(文字列を印刷する)= :グローバル配列は(そう一緒に結合するために)、 -(方向) = :方向、それぞれab cI
b¯J"1009001201301"n=4
cŽ9¦S[2,4,6,0][→,↓,←,↑]


1
50:4F°ÅP¯KIù.Δ1sЮθÅ¿Š®θÅ?Šθ)¯gè}©ˆ}ð¯2ô`€R«€¦J«Ž9¦SΛ 49:°ÅPIùć4FÐN1›iR}¦ˆθUKD.ΔÐθsXÅ?‚sXÅ¿ª¯gè]Ið¯J«Ž9¦SΛ 48:°ÅPIùćÐ4FˆθUKD.ΔÐθsXÅ?‚sXÅ¿ª¯gè}ÐNĀiR}¦}I¯JŽ9¦SΛ
グリムミー

@Grimyありがとう!とても素敵なゴルフ。に変更ÐθsXÅ?‚sXÅ¿ªすることで、48バイトバージョンに基づいてさらに2バイトを節約できましたθyXÅ?yXÅ¿))ループのスコープ内でなぜ機能するのかははっきりしていません。最初の反復でプライムリストもそのリストにラップすることを期待していたからです。しかし、それがなくても、yy代わりにを使用すると、Ðss1バイト節約されます。:)
ケビン・クルーッセン

4

05AB1E35 33 32 31バイト

-1バイト、Kevin Cruijssenに感謝

°ÅPIùΔÐXθÅ?Ïн©KX®¦«UNií]IXŽ9¦SΛ

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

説明:

°                 # 10 to the power of the input
 ÅP               # list of primes up to that
   Iù             # keep only those with the same length as the input

Δ                 # repeat until the list doesn't change
# This ends up doing a ton of unneeded work. 4F (to loop 4 times) would be
# enough, but Δ is shorter and the extra iterations don’t cause issues.
# At the start of each iteration, the stack only contains the list of primes,
# and the variable X contains the current list of digits we’ll want to print.
# Conveniently, X defaults to 1, which is our first digit.

 Ð    Ï           # push a filtered copy of the list, keeping only…
    Å?            # numbers that start with…
  Xθ              # the last character of X
       н          # get the first element: this is our next prime

 ©                # save this number to the register
  K               # remove it from the list of candidate primes
   X              # push X
    ®             # restore the number from the register
     ¦            # remove its first character
      «           # concatenate it to X
       U          # save the result to X

 Ni               # if N == 1 (second time through the loop)
   í              # reverse all elements in the list of candidate primes
    ]             # closes both this if and the main loop

      Λ           # Draw on a canvas…
I                 # using the input as length…
 X                # using X as the string to draw…
  Ž9¦S            # using [2,4,6,0] (aka [→,↓,←,↑]) as the directions to draw in

これは、ケビンの答えに部分的に基づいていますが、この時点では、コメントではなく独自の答えに値すると思うほど十分に異なっています。
グリムミー

1
私は今、この答えを見ています。非常に素晴らしい!一般的な方法(および最初と最後の部分)を除き、4つの素数の決定と文字列の構築は非常に異なる方法で行われるため、分離された答えを理解できます。私から+1。ところで、Θatを削除してバイトを保存できます。唯一の1truthyは05AB1Eであり、そうif Nif N == 1同じです。
ケビンクルーッセン

1
@KevinCruijssenありがとう!もちろんそれは知っていましたが、使用するのを忘れていました。振り返ってみると、Θiの05AB1E等価ですif (cond == true)...
Grimmy

はい、そうです。:) Θは、以外1をすべて変換したい場合に便利です0。ただし、ifステートメントではi、を使用した擬似コードのように実際には必要ありません== true
ケビンクルーッセン

2

JavaScript(ES8)、 205 ...  185177173 バイト

非常に非効率な素数テストのため、 TIOでタイムアウトします。n>8

n=>([a,b,c]=[0,-1,--n,0].map(p=o=i=>o[(g=n=>{for(k=n++;n%k--;);k|o[n]|p[i]-n%10?g(n):p=n+''})((~i?1:p%10)*10**n)|p]=p),[...p].map((d,i)=>i?i<n?d.padEnd(n)+b[i]:c:a).join`
`)

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

どうやって?

ステップ#1:4つの素数の計算

[a, b, c] =               // save the 3 first primes into a, b and c
                          // (the 4th prime will be saved in p)
  [ 0, -1, --n, 0 ]       // decrement n and iterate over [ 0, -1, n, 0 ]
  .map(p =                // initialize p (previous prime) to a non-numeric value
       o =                // use o as a lookup table
  i =>                    // for each value i in the list defined above:
    o[                    //   update o:
      (g = n => {         //     g = recursive function taking n
        for(k = n++;      //       set k = n and increment n
            n % k--;);    //       decrement k until it's a divisor of n
                          //       (notice that k is decremented *after* the test)
        k |               //       if k is not equal to 0 (i.e. n is not prime)
        o[n] |            //       or n was already used
        p[i] - n % 10 ?   //       or the last digit of n does not match the connected
                          //       digit (if any) with the previous prime:
          g(n)            //         do a recursive call
        :                 //       else:
          p = n + ''      //         stop recursion and save n coerced to a string into p
      })(                 //     initial call to g with:
        (~i ? 1 : p % 10) //       either 10 ** n if i is not equal to -1
        * 10 ** n         //       or (p % 10) * 10 ** n if i = -1
      ) | p               //     yield p
    ] = p                 //   set o[p] = p
  )                       // end of map()

ステップ#2:出力のフォーマット

[...p].map((d, i) =>      // for each digit d at position i in the last prime:
  i ?                     //   if this is not the first digit:
    i < n ?               //     if this is not the last digit:
      d.padEnd(n)         //       append d, followed by n - 1 spaces
      + b[i]              //       append the corresponding digit in the 2nd prime
    :                     //     else (last digit):
      c                   //       append the 3rd prime
  :                       //   else (first digit):
    a                     //     append the first prime
).join`\n`                // end of map(); join with carriage returns



1

JavaScript、484バイト

i=a=>a?(l=a=>a[(L=a=>a.length-1)(a)])(a)==9?i(r(a))+0:(r=a=>a.substr(0,L(a)))(a)+(+l(a)+1)%10:"1";s=(a,b)=>b?a==b?"":s(l(a)<l(b)?s(r(a),1):r(a),r(b))+Math.abs(l(a)-l(b)):a;m=(a,b)=>!a||!((c=L(a)-L(b))<0||!c&&a<b)&&m(s(a,b),b);p=(a,b="2")=>a/2<b||!(m(a,b)||!p(a,i(b)));a=>{for(M=1+(R=a=>"0".repeat(b))(z=a-1);!p(M=i(M)););for(N=M[z]+R(z);!p(N=i(N)););for(O=1+R(x=a-2);!p(O+n[z]);O=i(O));for(P=R(x);!p(m[0]+P+O[0]);P=i(P));for(S="\n",j=0;j<x;)S+=P[i]+R(x)+N[++i]+"\n";return M+S+O+N[z]}

最後の名前のない関数は、ASCIIアートを返します。

元のコード

function inc(a){
  if (!a) return "1";
  if (a[a.length-1]=="9") return inc(a.substr(0,a.length-1))+"0";
  return a.substr(0,a.length-1)+(+a[a.length-1]+1)%10;
}
function sub(a,b){
  if (!b) return a;
  if (a==b) return "";
  var v=a.substr(0,a.length-1);
  if (a[a.length-1]<b[b.length-1]) v=sub(v,1);
  return sub(v,b.substr(0,b.length-1))+Math.abs(a[a.length-1]-b[b.length-1])
}
function multof(a,b){
  if (!a) return true;
  if (a.length<b.length||a.length==b.length&&a<b) return false;
  return multof(sub(a,b),b);
}
function isprime(a){
  for (var i="2";a/2>i;i=inc(i)){
    if (multof(a,i)) return false;
  }
  return true;
}
function square(a){
  for (var m="1"+"0".repeat(a-1);!isprime(m);m=inc(m)){}
  for (var n=m[a-1]+"0".repeat(a-1);!isprime(n);n=inc(n)){}
  for (var o="1"+"0".repeat(a-2);!isprime(o+n[a-1]);o=inc(o)){}
  for (var p="0".repeat(a-2);!isprime(m[0]+p+o[0]);p=inc(p)){}
  var s="";
  for (var i=0;i<a-2;i++) s+=p[i]+"0".repeat(a-2)+n[i+1]+"\n";
  return m+"\n"+s+o+n[a-1];
}

最適かつ平均的な時間の複雑さ:Knuthのビッグオメガ表記のΩ(100 n n)(n桁の数字を減算するためのnステップ、分割可能性チェックごとに10 n減算、プライムチェックのための10 n分割可能性チェック、およびΩ(1)プライムチェック完了)。

最悪の複雑さ:Knuthのビッグオメガ表記のΩ(1000 n n)(n桁の数字を減算するためのnステップ、分割可能性チェックごとに10 n減算、プライムチェックのための10 n分割可能性チェック、および10 nプライムチェックが完了)

n=100約10 203の計算が必要だと思います。

サイドノート:UglifyJS 3を使用して構文を検証しました。これは、私が行ったよりもはるかに良く、47.13%を節約し、282バイトを獲得しました。しかし、私はそれが不正行為のように感じるので、そのスコアを作らないことに決めました。

i=(s=>s?9==(l=(l=>l[(L=(l=>l.length-1))(l)]))(s)?i(r(s))+0:(r=(l=>l.substr(0,L(l))))(s)+(+l(s)+1)%10:"1"),s=((L,i)=>i?L==i?"":s(l(L)<l(i)?s(r(L),1):r(L),r(i))+Math.abs(l(L)-l(i)):L),m=((l,r)=>!l||!((c=L(l)-L(r))<0||!c&&l<r)&&m(s(l,r),r)),p=((l,s="2")=>l/2<s||!(m(l,s)||!p(l,i(s))));

使用されないため、最後の関数を削除しました。実際には、追加された追加コードを含めて、削除されずに割り当てられた場合、さらに悪化しました。


3
これは不完全ですか?そして、ゴルフをしていませんか?
connectyourcharger

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