素数表


28

イントロ

私がレクリエーション数学で遊んだのは、数値の素数の除数を視覚的に比較/対比するための除数テーブルの構築です。入力番号のセットは列ラベルとして上部にあり、素数は行ラベルとして左側にあり、マークは2つの行の位置を示します。

たとえば、入力の場合、6, 9, 14, 22次のような表が作成されます。

    6  9 14 22
 2  *     *  *
 3  *  *
 7        *
11           *

これは、ある6の素因子を持っている239の素因子を持っている3ように、と。

建設

  • テーブルは、入力番号がスペースで区切られた昇順の列ラベルを形成するように構築され(事前にソートされていると想定できます)、行を形成する行ごとに1つずつ昇順で素数がリストされますラベル。
  • 数値の長さが異なる場合、すべての列が同じ幅で適切に整列するように、素数の先頭スペースと入力数値が必要になる場合があることに注意してください。
  • 各除数は単一*(または同じ文字がすべての出現に使用される限り、選択した他の適切なASCII文字)で表されます。
  • 複数の除数は無視されます(たとえば、その交差点には3 x 3 = 91つしかありません*)。
  • *限り、それは(私はすべての私の例を持っている明確なだとして、列の任意の場所に水平に配置することができ*右揃え)。

入力

  • それぞれの便利な形式の正の整数のリスト>1
  • 入力が事前にソートされていると想定できます。
  • 入力には一意の値のみが含まれることが保証されています。

出力

結果の素数表のASCIIアート表現。

ルール

  • 文字自体が正しく並んでいる限り、先頭または末尾の改行または空白はすべてオプションです。
  • 列/行の見出しを表形式のデータから分離する分割線を使用する方が短い場合は、それも許可されます。
  • 完全なプログラムまたは機能のいずれかが受け入れられます。関数の場合、出力する代わりに出力を返すことができます。
  • 可能であれば、オンラインテスト環境へのリンクを含めて、人々がコードを試せるようにしてください!
  • 標準的な抜け穴は禁止されています。
  • これはので、通常のゴルフルールがすべて適用され、最短のコード(バイト単位)が勝ちます。

6,9,14,22

    6  9 14 22
 2  *     *  *
 3  *  *
 7        *
11           *


2,3,5,7

  2 3 5 7
2 *
3   *
5     *
7       *

2,4,8,16,32

   2  4  8 16 32
2  *  *  *  *  *

75,99,151,153

     75  99 151 153
  3   *   *       *
  5   *
 11       *
 17               *
151           *

1
上の行と左の列の後に分割線を配置できますか?
ngenisis

@ngenisis確かに、私はそれを許可します。テーブルの正確な定式化は非常にオープンです。これは、この課題の正確な推理ではないためです。
AdmBorkBork

回答:


5

Mathematica、101 90バイト

11バイトを節約してくれたngenisisに感謝します!

TableForm[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}],TableHeadings->‌{f,g}]&

約3分の1の文字はU + 2223(3バイト)です。引数の可変数の名前のない関数は、それぞれが非ゼロの整数であり、次のようにTableFormオブジェクト(フォーマットされた出力)を返します。

TableForm出力

f=#&@@@FactorInteger[1##]f、任意の入力を分割するすべての素数のセットであると定義します(同等に、それらの積を分割します1##gが、入力で構成されるリストです。分割可能性に対応するsと空の文字列のOuter[If[#∣#2,Y,""]&,f,g]テーブルを作成しますYY文字列の代わりに未定義のトークンを使用する"Y""*"、2バイトを保存します)。次にTableForm[...,TableHeadings->‌{f,g}]、結果の配列を適切な行見出しと列見出しでフォーマットします。

以前の提出:

Grid[p=Prepend;Thread[q[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}]~p~g,f~p~""]]/.q->p]&

最初を省略でき""ます。
マーティンエンダー

2
TableForm[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}],TableHeadings->{f,g}]&分周器が許可されている場合
ngenisis

また、2番目に変更した場合も同様ですp[f,]
マーティンエンダー

ヘッダーを区切るグリッド線が許可されます。
AdmBorkBork

1
TableFormかっこいいです、うまくいけばそれは私のツールボックスにとどまります!
グレッグマーティン

3

ゼリー、18バイト

PÆfQ0;ðḍ€+W}⁸;"o⁶G

ルールで許可されている1ように*、の代わりに使用します。

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

使い方

PÆfQ0;ðḍ€+W}⁸;"o⁶G  Main link. Argument: A (array of integers greater than 1)

P                   Take the product of the integers in A.
 Æf                 Compute all prime factors (with multiplicity) of the product.
   Q                Unique; deduplicate the prime factors.
    0;              Prepend a 0. Let's call the result P.
      ð             Begin a new, dyadic chain. Left argument: P. Right argument: A
       ḍ€           Divisible each; for each p in P, test all integers in A for
                    divisibility by P. Yields one row of the shape of A for each p.
                    Note that the first element of P is 0, so the first row of the
                    resulting matrix contains only zeroes.
          W}        Wrap right; yield [A].
         +          Add the results to both sides. Because of how Jelly's auto-
                    vectorization works, this adds the first row of [A] (just A) to
                    the first row of the divisibility matrix (all zeroes) and
                    leaves the other rows untouched.
            ⁸;"     Prepend the elements of P to the corresponding rows of the
                    previous result.
               o⁶   OR space; replace all zeroes with spaces.
                 G  Grid; format the matrix as requested in the challenge spec.

2

ゼリー25 23 バイト

PÆfQ©ḍþµị⁾* ³;"Z⁶;®¤;"G

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

どうやって?

ÆE空の行を使用して除外する方が短い場合があります。

PÆfQ©ḍþµị⁾* ³;"Z⁶;®¤;"G - Main link: list of numbers, L
       µ                - monadic chain separation
P                       - product of L - multiply them all together
 Æf                     - prime factors (with repetitions, in ascending order)
   Q                    - unique items, maintaining order
                              - note that the product was performed to keep order
    ©                   - place in the register for later use, and yield
      þ                   - form the outer product of that and L using the dyad:
     ḍ                  -     isDivisor - 1 if divides, 0 if not
        ị⁾* <space      - index into "* " (1s to "*", 0s to " ")
            ³           - program's first input, L
             ;"         - zip with concatenation (column headers to the left)
               Z        - transpose (get it around the right way)
                   ¤    - nilad followed by link(s) as a nilad
                ⁶;®     - space (⁶) concatenated with (;) the register value (®)
                    ;"  - zip with concatenation (row labels to the left)
                      G - format the result as a grid (join items with spaces and
                                               rows with line feeds so they align)
                        - implicit print

2

JavaScript(ES6)、264 260 ... 179 173バイト

a=>[for(c of s=' '.repeat(w=a.slice(-1),i=0))if(!+(r=[i++?i:s,...i<2?a:a.map(x=>x%i&&c)].map(y=>(s+y).slice(-(w+1).length),a=a.map(d=x=>i<2|x%i?x:d(x/i))).join``))r].join`
`

このアプローチは現在、再帰的なアプローチ(現在178バイト)を永久に超えていると思います。

f=(a,i=0,w=a.slice(-1))=>i++-w?(+(r=[i<2?'':i,...i<2?a:a.map(x=>x%i&&' ')].map(y=>(' '.repeat(w)+y).slice(-(w+1).length)).join``)?'':r+`
`)+f(a.map(d=x=>i<2|x%i?x:d(x/i)),i,w):''

チャレンジで許可されているの0代わりに使用し*ます。

テストスニペット


私は間違っていない場合は、使用することができ|ますが、2つのブール値を比較しているので、...、if文で演算子を
ルーク

@ルークねえ、あなたは正しい。私は見逃していないことを確認する方法
ETHproductions

i<2チェックを.map関数内に移動する方が短くありませんか?
ルーク

@Lukeに変更...i<2?a:a.map(x=>x%i&&c)する場合...a.map(x=>i<2?x:x%i&&c)、それは短くありません。あなたが意味する場合にそれを移動する .map、多分...
ETHproductions

2

Python 2-197バイト

入力処理を簡単にし、文字列変換に ``を許可するためにPython 2に切り替えました。gmpy2次の素数の生成に使用します。出力形式は、以前のPython 3の提出に基づいています(以下を参照)。つまり、リストgをシンボルで埋めてフォーマットします。

import gmpy2
i=input()
n=len(i)+1
p=1;g=[' ']+i
while p<i[-1]:
 p=gmpy2.next_prime(p)
 t=['*'[m%p:]for m in i]
 if'*' in t:g+=[p]+t
print((('{:>%d}'%(len(`i[-1]`)+1)*n+'\n')*(len(g)/n)).format(*g))

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

説明

自分でデコードしたくない人のために。

import gmpy2                    # arithmetic library
i=input()
n=len(i)+1                      # saves bytes by not needing ()
                                # afterwards
p=1                             # starting number
g=[' ']+i                       # initialsing header row
while p<i[-1]:                  # looping until last character
  p=gmpy2.next_prime(p)         # get the next prime
  t=['*'[m%p:] for m in i]      # verify whether p is a 
                                # divisor of each number
  if'*'in t:g+=[p]+t            # if any divisor found, append
                                # p + divisors to g.
print(
    (('{:>%d}'%(len(`i[-1]`)+1) # compute right formatting element
                                # for length of last character + 1
        *n+'\n'                 # repeat for each input + once
                                # for the prime and add newline
     )*(len(g)/n)               # repeat row format until g
                                # can be inserted
    ).format(*g)                # format using g
)


Python 3-251バイト

誰かがもっとうまくやれると確信しています。素数を生成するためのこの回答に基づいて< k

i=list(map(int,input().split(',')))
l=len(str(i[-1]))+1
n=len(i)+1
g=[0]+i+sum([l for l in [[k]+[j%k==0for j in i]for k in range(2,i[-1])if all(k%f for f in range(2,k))]if 1in l],[])
print((('{:>%d}'%l*n+'\n')*(len(g)//n)).format(*g).replace('0',' '))

非ゴルフバージョンと説明が続きます。


4
PPCGへようこそ!
AdmBorkBork

1
代わりにi=list(map(int,input().split(',')))、あなたはただやることができi=input()て、フォームで入力をします[1, 2, 3, 4]
nedla2004

おかげで、私はそれを知りませんでした。しかし、とにかく後でそれを作り直すつもりです:)。
PidgeyUsedGust

で2バイト節約できp=gmpy2.next_prime(p);t=['*'[m%p:]for m in i]、のスペースを削除できますif"*" in
トレルゼビル

1

Mathematica、165バイト

むしろ冗長-多分誰かがそれで何かをすることができます:

(j=Join;a=#[[All,1]]&/@FactorInteger@#;b=Sort@DeleteDuplicates@Flatten@a;Grid[j[{j[{""},#]},Transpose@j[{b},Table[If[MemberQ[a[[t]],#],"*",""]&/@b,{t,Length@a}]]]])&


1

パイソン2181 179バイト

FlipTackのおかげで-2バイト

n=input()
p=[]
t="%%%ss "%len(`n[-1]`)*-~len(n)
print t%(('',)+n)
i=2
while n[-1]/i:
 if all(i%j for j in p):
	p+=[i];s=['*'[m%i:]for m in n]
	if'*'in s:print t%tuple([i]+s)
 i+=1

入力はタプルでなければなりません。
オンラインでお試しください!


all(i%j for j in p)使用する代わりに機能しmapますか?
FlipTack

@FlipTackはい、それは良かったのですが、私はいくつかのことを変更し、これを更新するのを忘れました
ロッド

1

バッチ、451バイト

@echo off
set/am=0,w=2,p=1
for %%n in (%*)do set/a"n=m-%%n,m+=(n>>31)*n
for /l %%i in (0,1,9)do set/am/=10,w+=!!m
set s=
for %%n in ("" %*)do set t=%%~n&call:t
set v=%*
:g
if not %s: =%==%p% echo%s%
if %m%==1 exit/b
set/at=p+=1,m=0
set s=
call:t
set v=&for %%n in (%v%)do set n=%%n&set t=&call:c
goto g
:c
set/ar=n%%p
if %r%==0 set/an/=p&set t=*&goto c
set/a"m|=n
set v=%v% %n%
:t
set t=           %t%
call set s=%%s%%%%t:~-%w%%%

説明:w入力値の最大値を介してフィールド幅を計算することから始めますmwサブルーチンを使用して、空の文字列と入力番号を幅にパディングして、出力の最初の行を生成しますt。次に、2から始まる整数をループ処理し、整数をパディングして出力の行を生成し、サブルーチンcを呼び出して各値に応じて空の文字列またはアスタリスクをパディングしますが、アスタリスクが含まれていない場合、生成された行はスキップされます。出力が生成されると、各値は、余りになるまで整数で除算されるため、1より大きい値がなくなるとループが終了します。

ように注意しset v=実行されます%v%に代入するfor同じ行にループ。


1

パイソン2157の 148 146 145 143バイト

def p(*t):print'%%%ds '%len(`x[-1]`)*len(t)%t
def f(x):k=m=1;p(' ',*x);exec"r=[n%k and' 'for n in x]\nif 0in m%k*r:p(k,*r)\nm*=k*k;k+=1;"*x[-1]

ルールで許可されている0ように*、の代わりに使用します。

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

バックグラウンド

素数を特定するために、ウィルソンの定理の帰納法を使用します。

ウィルソンの定理の帰結

使い方

最初の行は、ヘルパー関数を定義します。

def p(*t):print'%%%ds '%len(`x[-1]`)*len(t)%t

pは、タプルtに格納する可変数の引数を取ります。

'%%%ds '%len(`x[-1]`)書式文字列を構築するために書式文字列を使用しています。%%はリテラルのパーセント記号で%dあり、len(`x[-1]`)返される整数のプレースホルダーです。つまり、の最後の要素の桁数です。 x(まだ定義されていない入力)リテラルです。

例えば、場合、最後の要素xが 3桁、この利回りを持って%3s いる、*len(t)のすべての要素のために一度繰り返しのx。最後に、%tその書式文字列をタプルtに適用し、次の文字列を作成します、スペースで区切られ、特定の長さにすべて右揃えされたtの要素の。

2行目は、実際の送信を定義します。入力としてリストxを受け取る関数fです。交換した後、それは先行する文字列の実行文で、回ループを、私たちは、次のコードを取得します。execx[-1]for

def f(x):
    k=m=1;p(' ',*x)
    for _ in range(x[-1]):
        r=[n%k and' 'for n in x]
        if 0in m%k*r:p(k,*r)
        m*=k*k;k+=1

まず、fはkm1に初期化します。ご了承ください(K - 1)!= 0!= 1 = M

次に、関数を使用してp(' ',*x)、スペースとxの整数を出力します p

次に、ループに入り、残りの出力を印刷します。

まず、r=[n%k and' 'for n in x]各整数の余りのリスト構築のnにおけるXで割っkは。正の剰余、つまりkの倍数に対応しない剰余は真実であり、スペースで置き換えられand' 'ます。

次に、を構築しm%k*rます。以降、M =(k - 1)!、ウィルソンの定理の帰結により、これはkが素数の場合は単純にrですが、そうでない場合は空のリストになります。結果に少なくとも1つの0がある場合、つまり、kが素数でxの少なくとも1つの整数がkで割り切れる場合、Trueを返し、呼び出され、kと分割可能性インジケータを出力します。0in m%k*rp(k,*r)0割り切れる場合はスペース。

最後に、mを乗算してkをインクリメントします。したがって、品質m =(k-1)です。保持し続けます。


1

MATL、31バイト

pYfu!Gy\~h0GhwvVZ{'(?<!\d)0'0YX

これは、チャレンジで許可されているの1代わりにを使用*します。

オンラインでお試しください!または、すべてのテストケースを確認します

説明(古い

p           % Implictly input array of numbers. Push product of array
Yf          % Prime factors as a row vector
u           % Keep only unique values
!           % Transpose into column vector
G           % Push input again
y           % Duplicate column vector of unique prime factors onto top
\           % Modulo, element-wise with broadcast
~           % Negate
h           % Concatenate horizontally
0           % Push 0
G           % Push input again
h           % Concatenate horizontally
w           % Swap
v           % Concatenate vertically
V           % Char array representation
Z{          % Convert to cell array of strings. Each row gives a string
'(?<!\d)0'  % Push this string: match '0' not preceded by a digit
0           % Push this string: '0' will be replaced by char 0
YX          % Regexp replace
            % Implicit inoput. Char 0 is displayed as space

0

ラケット176バイト

(let((p printf))(display"   ")(for((x nl))(p" ~a " x))(displayln"")(for((i '(2 3 7 11)))
(p"~a  " i)(for((j nl))(if(member i(prime-divisors j))(p" * ")(p"   ")))(displayln"")))

ゴルフをしていない:

(define (f nl)
  (let ((p printf))

    (display "   ")
    (for ((x nl))
      (p " ~a " x))
    (displayln "")

    (for ((i '(2 3 7 11)))
      (p "~a  " i)
      (for ((j nl))
        (if (member i (prime-divisors j))
            (p " * ")
            (p "   ")))
      (displayln ""))))

テスト:

(f '(6 9 14 22))

出力:

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