タートルプライムですか?


28

みんな知っているように、それはずっとです。しかし、それはずっと下のプライムですか?

数値は、次の条件を満たす場合、「タートルプライム」と見なされます。

1) It is prime.
2) It is possible to remove a single digit leaving a prime number.
3) Step 2 can be repeated until left with a single digit prime.

たとえば、239は「タートルプライム」です。これは、23どちらか2またはに縮小できるため3、両方ともプライムです。それはまたに低減することができ29、その後2151タートルプライムではありません。(プライムではない15)、51(プライムではない)、またはになり11ます。11は素数ですが、に減らすことができますが1、そうではありません。

正の整数を指定して、それが「タートルプライム」かどうかを判断します。出力は、trueまたはfalseの値に対して同じ出力を提供する限り、どのような形式でもかまいません。

テストケース:

input -> output
1     -> false
2     -> true
17    -> true
19    -> false
239   -> true
389   -> false

得点

これはなので、各言語で最短の答えが勝ちです!



@MagicOctopusUrn WOW
Keyuガン


3
入力を数字のリストとして取得できますか?
完全に人間

1
あなたの条件は、すべての1桁の素数がタートル素数ではないことを示しています。条件2は失敗します。数字のみを削除しても何も残らないため、数字を削除しても素数を残すことはできません。
hvd

回答:


6

ゼリー、16バイト

DŒPḊṖLÐṀḌ߀¬Ȧ<ÆP

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

使い方

DŒPḊṖLÐṀḌ߀¬Ȧ<ÆP  Main link. Argument: n

D                 Decimal; convert n to base 10.
 ŒP               Powerset; get all sub-arrays of n's decimal digits.
   Ḋ              Dequeue; remove the first sub-array (empty array).
    Ṗ             Pop; remove the last sub-array (all of n's digits).
     LÐṀ          Maximal by length; keep those of the remaining subarrays that
                  have maximal length. This keep exactly those sub-arrays that have
                  one (and only one) digit removed. If n < 10, this yields an empty
                  array. Without Ḋ, it would yield [[]] instead.
        Ḍ         Undecimal; turn the generated digit arrays into integers.
         ߀       Recursively map the main link over the generated integers.
           ¬      Negate; map 1 to 0 and 0 to 1.
            Ȧ     Any and all; yield 0 if the array is empty (n < 10) or any of the
                  recursive calls returned 1 (mapped to 0). If all calls returned
                  0, this will yield 1.
              ÆP  Test n for primality, yielding 1 for primes, 0 otherwise.
             <    Test if the result to the left is less than the result to the
                  right. This is possible only if the left result is 0 (n < 10 or
                  removing a digit results in a turtle prime) and the right result
                  is 1 (n itself is prime).

もっと魔法のゼリー!男は、このようなものは...どこにでも取得
coinheringaahing caird

7

Haskell104 102 99 98 97 95 91バイト

p x=product[2..x-1]^2`mod`x>0
f[]=1>0
f x|y<-zip[0..]x=or[f[snd b|b<-y,b/=a]|a<-y,p$read x]

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

説明

まず、素数テストを設定します

p x=product[2..x-1]^2`mod`x>0

これは、ウィルソンの定理を使用して入力の素数性を決定します。

次に、空の文字列が真実であることを主張する基本ケースを宣言します。

f[]=1>0

次に、実際の関数を定義します

f x|y<-zip[0..]x=or[f[snd b|b<-y,b/=a]|a<-y,p$read x]

パターンガードを使用してにバインドzip[0..]xyます。後で2回使用する必要があるためです。次に、答えは

or[f[snd b|b<-y,b/=a]|a<-y,p$read x]

[[snd b|b<-y,b/=a]|a<-y]入力から削除された数字であるすべての数字です。それで、これらの数字の少なくとも1つが真実であると断言していfます。合成数が偽物であることを保証するために、を追加しprime$read xます。数が素数でない場合、リストは空になり、any空のリストはfalseになります。


1
-2バイト:any f[[or[f[
アンダースKaseorg

1
-4バイト:[b|(i,b)<-y,i/=a]|(a,_)<-y[snd b|b<-y,b/=a]|a<-y
アンダースKaseorg

6

R、124 122 120 113 95 93 106 105バイト

 g=pryr::f(`if`(gmp::isprime(sum(x*10^((l<-sum(x|1)-1):0))),any(!l,sapply(0:l+1,function(z)g(x[-z]))),!1))

関数に評価する:

function (x) 
if (gmp::isprime(sum(x * 10^((l <- sum(x | 1) - 1):0)))) any(!l, 
    sapply(0:l + 1, function(z) g(x[-z]))) else !1

再帰的なソリューション。入力を数字のリストとして受け取ります。

2つの論理ステートメントがあります。

  1. x連結すると素数ですか?

  2. 次のいずれかですTRUE

    1. 長さはx非ゼロですか?これが最終的な終了条件です。

    2. f TRUEサブセット用xですか?

最初のステートメントは、素数のみを使用し続けることを保証します。2番目は実際の再帰を行います。

@Giuseppeのおかげで2バイト節約されました。

バグのためにゴルフの一部を元に戻さなければなりませんでした。以前の関数定義を誤ってテストしていたためです。

R、98バイト、非競合

コメントで述べたように、パッケージを作成しました。チャレンジはそれより前に行われていたため、これは競合するものではありませんが、少し紹介したかったのです。それほど遠くはありませんが、私たちはそこに着きます。

g=pryr::f(`if`(gmp::isprime(RG::C(x)),any(!(l<-sum(x|1)-1),sapply(0:l+1,function(z)g(x[-z]))),!1))

C() パッケージの最初の関数であり、数字を数値に連結する処理を行います。


これらの操作のいくつか(あなたを見てsum(x*10^(((l<-sum(x|1))-1):0)))は、とてつもない言葉遣いです。私は本当にゴルフパッケージを作成することを検討していますR
JAD

これが私の解決策だっただろうが、私は周りに私の頭をラップすることができませんでしたsapply...また、私はあなたがしたいかもしれないと思うf=pryr::f(...)か、他あなたが使用する必要がありますfsapply
ジュゼッペ

1
@Giuseppeすべての単一文字の名前:Dパッケージgなどを呼び出してみませんか?
JAD

1
@Giuseppeパッケージの開始を作成しました:p見てください:github.com/JarkoDubbeldam/RG
JAD

1
@JarkoDubbeldam美しい。今後の課題により、追加する必要がある機能が明らかになると確信しています。文字列の操作は大きく、何かのためにel(strsplit(x,''))大量のバイトを節約できます。
BLT

5

ゼリー、19バイト

DJḟЀ`ịDḌḟ0߀¬Ȧ¬aÆP

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

使い方

DJḟЀ`ịDḌḟ0߀¬Ȧ¬aÆP                input:239

D                    decimal         [2,3,9]
 J                   range@length    [1,2,3]
  ḟЀ`               filter out each [[2,3],[1,3],[1,2]]
      ịD             index&decimal   [[3,9],[2,9],[2,3]]
        Ḍ            undecimal       [39,29,23]
         ḟ0          filter out 0    [39,29,23]
           ߀        this@each       [1,1,1]
             ¬       logical not     [0,0,0]
              Ȧ      any and all     0
               ¬     logical not     1
                aÆP  and&is_prime    1

基本ケースftwなしの再帰。


3

ゼリー27 26 バイト

DµœcL’$Ḍµ€FÆPÐf
×⁵WÇÐĿFṪ<8

整数を取得および返すモナドリンク(そうでない場合1はturtle用0)。

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

どうやって?

DµœcL’$Ḍµ€FÆPÐf  Link 1: primes by digit removal: list of numbers  e.g. [19790]
D                cast to decimal list (vectorises)                      [[1,9,7,9,0]]
 µ      µ€       monadic chain for €ach:
      $            last two links as a monad:
    L                length                                             5
     ’               decrement                                          4
  œc             combinations without replacement                       [[1,9,7,9],[1,9,7,0],[1,9,9,0],[1,7,9,0],[9,7,9,0]]
       Ḍ         cast from decimal list (vectorises)                    [1979,1970,1990,1790,9790]
          F      flatten (from a list of lists form the for €ach to a single list)
             Ðf  filter keep if:
           ÆP      is prime?

×⁵WÇÐĿFṪ<8  Main Link: number, n             e.g. 1979
 ⁵          literal 10
×           multiply                              19790
              (this is so the first number is tested as prime too)
  W         wrap in a list                        [19790]
    ÐĿ      loop, collecting results (including the input×10) while change still occurs:
   Ç          call the last (1) link as a monad   [[19790],[1979],[197,199,179],[19,17,97,19,19,17,19,79],[7,7,7,7],[]]
      F     flatten                               [19790,1979,197,199,179,19,17,97,19,19,17,19,79,7,7,7,7]
       Ṫ    tail                                  7
        <8  less than 8?                          1
              (if a single digit prime was reached this will be 1
               otherwise it will be 0
               e.g. an input of 4 yields 40 at the end which is not <8)

1
2つの実質的に異なるJellyの回答を見ることは興味深いです。誰が彼らをより小さくすることができるかを見てみましょう。
主ファルカード

2

ルビー72 57 + 8 = 80 65バイト

-rprimeフラグを使用します。histcratから-15バイト!

f=->n{n==''||n.to_i.prime?&!n.scan(/./){f[$`+$']&&break}}

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


&&!!just &に置き換えることができ、結果をブール値にキャストします。あなたの再帰呼び出しもperlismsを使用して少し短い得ることができます:!n.scan(/./){f[$`+$']&&break}}
histocrat

@histocratああ、はい、私は実際には初期状態のためにその最後の部分にブール短絡を必要としないことを忘れていました。n.scanトリックが機能する理由を知っていますか?
値インク

1
ええ、そこにある2つのグローバル変数は、最新の一致の左右の文字列に設定されているため、それらを連結すると文字列から1文字を引いたものが得られます。繰り返しの各ポイントで状態が必要なので、のようなことはできませんが.scan.find、成功すると手動でループを抜けることができます。中断した場合、をscan返しますnil。それ以外の場合は、常に真実の文字列を返します。
histocrat

2

Java、220バイト

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

ゴルフ:

boolean t(String n){int l=n.length();if(f(x->{for(int i=2;i<x;)if(x%i++==0)return 1<0;return x>1;},new Integer(n)))if(l<2)return 1>0;else for(int i=0;i<l;)if(t(n.substring(0,i)+n.substring(++i,l)))return 1>0;return 1<0;}

ゴルフをしていない:

  boolean t(String n) {
    int l = n.length();
    if (f(x -> {
      for (int i = 2; i < x;) {
        if (x % i++ == 0) {
          return 1 < 0;
        }
      }
      return x > 1;
    } , new Integer(n))) {
      if (l < 2) {
        return 1 > 0;
      }
      else {
        for (int i = 0; i < l;) {
          if (t(n.substring(0, i) + n.substring(++i, l))) {
            return 1 > 0;
          }
        }
      }
    }
    return 1 < 0;
  }

以前のコメントを無視します。しかし、あなたはこれにゴルフすることができます:boolean t(String n){int l=n.length(),x=new Integer(n),i;for(i=2;i<x;x=x%i++<1?0:x);if(x>1)if(l<2)return 1>0;else for(i=0;i<l;)if(t(n.substring(0,i)+n.substring(++i,l)))return 1>0;return 1<0;}191バイト
ケビンクルーッセン

trueとfalseの代わりに1と0を返すことで、いくつかのバイトを節約できます。
ネベイ

@NevayこれはC ++では機能しますが、Javaでは機能しません。整数を暗黙的にブール値に変換することはできません。

1
よくわかりませんが、fどこから来たのですか?
ローマングラフ

質問は、true / falseに任意の値を使用できることを示しています。メソッドのブール値の結果が必要な唯一の場所は、最後のif条件(>0intをブール値に変換するために追加できる)で、Kevin Cruijssenのバージョンでは2 * 2 + 1 * 4 = 8バイトを節約できます。
ネヴァイ

1

05AB1E28 27バイト

反復ソリューション。

¸[D0èg2‹#εæ¨D€gZQÏDpÏ}˜]p1å

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

説明

¸                              # wrap input in a list
 [                             # start a loop
  D0èg2‹#                      # if the length of the first element is less than 2, break
         ε                     # apply to each element in the list
          æ                    # compute powerset
           ¨                   # remove last element (the full number)
            D€gZQÏ             # keep only the elements whose length is the max length
                  DpÏ          # keep only primes
                     }         # end apply
                      ˜        # flatten list
                       ]       # end loop
                        p1å    # is any element in the resulting list prime

1

パイソン2132の 124 119バイト

-8 @WheatWizardに感謝

-5 @LeakyNunに感謝

p=lambda i:i>1and all(i%v for v in range(2,i))
f=lambda n:n<'0'or any(f(n[:i]+n[i+1:])for i in range(len(n)))*p(int(n))

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

組み込みのプライムチェッカーがなければ、それを磨くものは考えられません。数値を文字列として取得し(OPで数字のリストが許可されていると仮定しますが、そうでない場合は別のラムダで+14バイト)、各「タートル」数値のタートルネスを再帰的に計算します。



f=lambda n,i=0:n==''or p(int(n))and i<len(n)and(f(n[:i]+n[i+1:])or f(n,i+1))バイトを節約できると思います。Pythonのゴルフスキルが優れている人は、おそらくそれをさらに短縮できます。
ニール

@ Neil、1バイトを節約しますが、他の場合のように1を入力するとFalseの代わりに0が返されるため、「-8の素数チェックのために」「真偽値または偽値の同じ出力」という言葉はそれを取ることを防ぎます。OPが(同義ではあるが)異なる出力を許可する場合、それを変更します。
アーノルドパーマー

1
申し訳ありませんが、以前の提案は無効です。119バイト
漏れ修道女

1

C#、355バイト

namespace System{using B=Numerics.BigInteger;class A{static void Main(){Console.WriteLine(D(Console.ReadLine()));}static bool P(B x){if(x<2)return 1<0;B r=1;for(int i=1;i<=x-1;i++)r*=i;return(r+1)%x==0;}static bool D(string x){if(x.Length==0)return 1>0;bool b;if(b=P(B.Parse(x))){var n=1<0;for(int i=0;i<x.Length;i++)n|=D(x.Remove(i,1));b&=n;}return b;}}}

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

私の最初のコードゴルフですので、うまくやったことを願っています。それをさらに小さくする方法は考えられませんでした(BigIntegerの代わりにintを使用する以外は、提供されたすべてのテストケースで機能するようにしました)。とにかく、適切にフォーマットされた同じものがあります:

namespace System
{
    using B = Numerics.BigInteger;
    class A
    {
        static void Main()
        {
            Console.WriteLine(D(Console.ReadLine()));
        }

        static bool P(B x)
        {
            if (x < 2)
                return 1<0;
            B r = 1;
            for (int i = 1; i <= x - 1; i++)
                r *= i;
            return (r + 1) % x == 0;
        }

        static bool D(string x)
        {
            if (x.Length == 0)
                return 1>0;
            bool b;
            if (b = P(B.Parse(x)))
            {
                var n = 1<0;
                for (int i = 0; i < x.Length; i++)
                    n |= D(x.Remove(i, 1));
                b &= n;
            }
            return b;
        }
    }
}


0

PHP、164バイト

function t($n){for($i=1;++$i<$n;)if($n%$i<1)return 0;if($n<10)return $n>1;foreach($r=str_split($n)as$k=>$v){$q=$r;array_splice($q,$k,1);$z|=t(join($q));}return $z;}

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

素数の数をテストすることから始めて、配列として数字をループし、各数字をポップし、残りを一緒に結合し、関数を通して再帰的に再び送ります。下向きの各リンクは、trueすべての素数のパスが少なくとも1つ存在する場合にのみ、下位パスと論理ORを実行します。


0

Javascript 167バイト

n=>{a=[];for(i=1;i++<=n;)a.every(x=>i%x)?a.push(i):0;b=k=>(s=''+k,a.indexOf(k)>-1&&(k<10||[...s].some((x,i)=>(r=[...s],r.splice(i,1),b(~~(r.join('')))))));return b(n)}

説明

n=>{
    a=[];                             // create array to store primes in
    for(i=1;i++<=n;)                  // iterate from 2 to n
        a.every(x=>i%x)?a.push(i):0;  // if i % x is truthy for all x in a,
                                      // then i is prime
    b=k=>(                            // function to test is k is turtle prime
        s=''+k,                       // convert k to a string
        a.indexOf(k)>-1 && (          // if k is prime and
            k<10 ||                   // k is a single digit or
            [...s].some((x,i)=>(      // iterate over the digits of k
                                      // and check to see if, by removing each
                                      // any of the resulting numbers is turtle prime
                                      // ... is spread operator
                                      // [...s] converts string s to an array of characters 
                r=[...s],             // convert s to an array again,
                                      // importantly, this cannot be the same array
                                      // we created above, as we need to
                r.splice(i,1),        // splice out the ith element of the array
                b(~~(r.join('')))     // join the array to a string, convert to int,
                                      // and check if this number is turtle prime
                                      // ~ is bitwise negate, implicitly converts to int first before negating
                                      // ~~ negates the negation, getting us the int
            ))
        )
    );
    return b(n)
}

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