Imprime / imprime todos los números positivos en los que cada subcadena de varios dígitos en su representación decimal también es primo.

15

Tarea

Su tarea es imprimir o generar todos los números positivos en los que cada subcadena de varios dígitos en su representación decimal también es primo. Si el número tiene al menos 2 dígitos, esto implicaría que el número en sí también debe ser primo.

Ejemplo

  • 6197es en la secuencia porque cada subcadena de varios dígitos en 6197es primo, a saber: 61, 19, 97, 619, 197, 6197(sí).
  • Tenga en cuenta que 6no es un primo, pero 6197todavía está en la secuencia porque 6no es una subcadena de varios dígitos de 6197.
  • 8también está en la secuencia porque cada subcadena de varios dígitos en 8es primo. No hay una subcadena de varios dígitos 8, por lo que este es un caso de verdad vacía .

Especificaciones

  • Se aplican las lagunas estándar , excepto que se le permite codificar la salida o almacenar información relacionada con la salida en su programa.
  • Los números en la salida pueden estar en cualquier orden .
  • Los números en la salida pueden tener duplicados.
  • Puede usar cualquier separador , si elige imprimir en lugar de imprimir.
  • Se le permite prefijar y / o postfijar la salida si elige imprimir en lugar de la salida.
  • El separador y el prefijo y el postfix no pueden contener ningún dígito (U + 0030 a U + 0039).

Lista completa (58 artículos)

1
2
3
4
5
6
7
8
9
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
113
131
137
173
179
197
311
313
317
373
379
419
431
479
613
617
619
673
719
797
971
1373
3137
3797
6131
6173
6197
9719

Referencia


Como siempre, siéntase libre de abordar en los comentarios cualquier cosa que deba aclarar.

Monja permeable
fuente
2
Daré una recompensa de +300 a cualquiera, excepto a @Fatalize, que envíe la respuesta más pequeña a este desafío en Brachylog ( enlace wiki ) ( enlace TIO ) ( sala de chat ).
Leaky Nun
2
Pobre @Fatalizar. Eso es lo que obtienes por crear un lenguaje
Luis Mendo
3
Tengo una respuesta de 50 bytes :(
Fatalize
1
¿Debe finalizar el programa?
Fatalize
2
@LeakyNun ¡Parece que alguien va a obtener esa recompensa!
Jordania

Respuestas:

7

05AB1E , 15 13 bytes

Código:

4°GN§ŒD9›ÏpP–

Explicación:

  G            # For N in range 1,
4°             #   10000
   N           # Push N
    §          # Convert that to string
     Π        # Get all substrings
      D9›Ï     # Keep all substrings that are greater than 9
          p    # Check each of them if they are prime
           P   # Product
            –  # If 1, print N

Utiliza la codificación CP-1252 . Pruébalo en línea! (puede tomar unos segundos)

Adnan
fuente
5

Brachylog , 18 17 15 16 15 bytes

ℕ₁<l4&≜sᶠ{Ḋ|ṗ}ᵐ

Pruébalo en línea!

-1 byte después de una discusión con Fatalize me inspiró a ver qué pasa si cambio el ly el <alrededor.

Este predicado genera la salida a través de la variable de entrada, siempre que la variable de salida se deje sin restricciones. Como se permiten duplicados, cada número se genera con una multiplicidad igual a 2 a la potencia del número de sus dígitos que son números primos.

ℕ₁                 The input variable is a natural number
  <                less than
   l4              some number with length 4 (maximized as 9999).
     &≜            Assign a number to the input, and assert that
       sᶠ          every substring of it
         { | }ᵐ    is either
            ṗ      a prime number
          Ḋ        or a single digit.

Versiones anteriores:

{≜ℕsᶠ{Ḋ!|ṗ}ᵐ&}ᶠ⁵⁹b
7^₅⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ
8ḟ⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ
∧8ḟ>?ℕ₁≜sᶠ{Ḋ|ṗ}ᵐ
Cadena no relacionada
fuente
Esto es de 16 bytes, pero no se ha probado, porque verificar todo hasta 40320 no es exactamente rápido:8ḟ⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ
Cadena no relacionada
Sin embargo, termina bien dado un límite superior de 10000: tio.run/##SypKTM6ozMlPN/r/39AACB7NX/…
Cadena no relacionada
4

Brachylog , 18 bytes

Otra solución de Brachylog. No pude hacerlo más corto que la solución Brachylog de Erik The Outgolfer; tiene exactamente la misma longitud, pero se acerca a la generación desde la dirección opuesta.

{≜ℕ{sℕ₁₀}ᶠṗᵐ&}ᶠ⁵⁹b

Parece que Unrelated String ha superado esto por muchos personajes, a quienes felicito.

Explicación:

{≜ℕ                Brute force all nonnegative integers to find any that match the constraints
   {s               Create a predicate that finds all subsequences of digits of said integer
     ℕ₁₀            Constrains those subsequences to be >= 10
        }ᶠ          Finds all possible values of that predicate: all multi-digit subsequences
          ṗᵐ        Apply a primality constraint to all of those subsequences
            &       Make the predicate output the input integer rather than a prime subsequence
             }ᶠ⁵⁹   Find the first 59 results (all of the puzzle's solutions, and zero)
                 b  Remove the first element of the list, i.e. 0

Pruébalo en línea!

IFcoltransG
fuente
3

Jalea , 17 bytes

DẆṖÐfḌÆP€Ạ
³²RÇÐf

Mi primera respuesta Jelly! ¡Guardado 3 bytes gracias a @Leaky Nun !

Pruébalo en línea

Explicación:

DẆṖÐfḌÆP€Ạ      The helper link, which checks if a given number satisfy the conditions.
DẆ              Convert the argument to a list of its digits and get all its substrings.
  ṖÐf           Remove all lists of length 1.
     ḌÆP€Ạ      Convert back each element to an integer and check if all of them are prime.

³²RÇÐf          Main link.
³²              Create a 100 and square it, which gives 10000.
  R             Create a list from 1 to it.
   ÇÐf          Filter out all the elements where the helper link gives false.
Loovjo
fuente
¡Felicitaciones por tu primera respuesta de Jelly!
Leaky Nun
2
RÇÐfpuede ser reemplazado con Ç€T. ṖÐfḌÆP€puede ser reemplazado con ḌḟDÆP.
Dennis
3

Java 8, 182 bytes

v->{for(int n=0;++n<1e4;)if(P(n)>0)System.out.println(n);}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}int P(int n){return n>99?p(n)*p(n%100)*p(n%1000)*P(n/10):n<10?n:p(n);}

La respuesta C (gcc) del puerto de gastropner , ¡así que asegúrese de votar su respuesta!

Pruébalo en línea.

Explicación:

// Loop in range [1,10000), and print any primes corresponding to the challenge description
v->{for(int n=0;++n<1e4;)if(P(n)>0)System.out.println(n);}

// Checks if the given integer is a prime (return unchanged input if prime, 0 if not)
int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

// Recursive method that checks if every part of length 2+ is a prime, or is below 10
int P(int n){return n>99?p(n)*p(n%100)*p(n%1000)*P(n/10):n<10?n:p(n);}
Kevin Cruijssen
fuente
2

PowerShell v2 +, 107104 bytes

1..10+(11..1e4|?{($x=11..($i=$_)|?{"$i"-match$_}).count-eq($x|?{'1'*$_-match'^(?!(..+)\1+$)..'}).count})

Advertencia: un poco lento

Recorre de 11a 1e4(es decir, 10000) y extrae números con el Where-Objectselector ( |?{...}). La cláusula consta de dos componentes: los primeros bucles desde 11hasta el número actual y se utilizan Where-Objectpara extraer aquellos números que forman una subcadena del número actual (a través del -matchoperador de expresiones regulares). Almacenamos esas subcadenas en $x. La segunda parte se repite $xy se usa Where-Objectpara extraer todos los números primos utilizando la expresión regular principal . Luego tomamos los .countdos y la verificación es en realidad si son -eqreales. Por ejemplo, 971tendrá $x = (71,97,971)y cada uno de ellos son primos, por lo que 3-eq3es $TRUEy , por lo tanto 971, será seleccionado.

Ese resultado se concatena con un rango 1..10. La matriz resultante se deja en la tubería y la salida es implícita, con una nueva línea entre los elementos por defecto.

AdmBorkBork
fuente
2

C (gcc) , 144 142 140 136 134 132 bytes

-2 gracias a Kevin Cruijssen. -2 gracias a ceilingcat

... E inspirado por eso, podemos obtener otros 2 bytes del bucle for.

También desvergonzó descaradamente al mejor corrector de la respuesta de Kevin Cruijssen por otro -4.

p(n,i){for(i=2;i<n;)n*=n%i++||n<10;i=n;}P(n){n=p(n)*(n<99||p(n%100)*p(n%1000)*P(n/10));}f(n){for(n=1e4;--n;)P(n)&&printf("%d\n",n);}

Pruébalo en línea!

gastropner
fuente
||n<10puede ser |n<10y for(n=1;n<1e4;n++)puede ser for(n=0;++n<1e4;)para -2 bytes.
Kevin Cruijssen
@KevinCruijssen ¡Salud!
Gastropner
2

Malbolge Unshackled (variante de rotación de 20 trits), 2,5254e7 bytes o 1,9809e7 bytes

El tamaño de esta respuesta excede el tamaño máximo de programa postable (eh), por lo que el código se encuentra en mi repositorio de GitHub (nota: no copie el código usando CTRL + A y CTRL + C, solo haga clic derecho y haga clic en "Guardar elemento de destino como. .. ").

¿Cómo ejecutar esto?

Esto podría ser una parte difícil, porque el ingenuo intérprete de Haskell tardará siglos en ejecutarlo. TIO tiene un intérprete decente Malbogle Unshackled, pero lamentablemente no podré usarlo (limitaciones).

La mejor que pude encontrar es la variante de ancho de rotación fija de 20 trits, que funciona muy bien.

Para hacer que el intérprete sea un poco más rápido, eliminé todas las comprobaciones del intérprete Malbolge Unshackled de Matthias Lutter.

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

Notas de rendimiento

La aplicación ejecutó unos 40 minutos en mi máquina, produciendo números HEX de la secuencia. Lo detuve alrededor de una hora de cálculos, y terminó en 0x11.

Tenga en cuenta que esta respuesta difiere de mi otra, porque esta realmente calcula los números, y se puede hacer para que los calcule indefinidamente.

La aplicación asigna el búfer de rotación, que tiene alrededor de 7 gigabytes de tamaño, así que prepara mejor tu RAM libre.

Variante alternativa

La variante alternativa usa alrededor de 2 gigabytes de memoria menos, pero produce la salida en forma de caracteres ASCII (0 = ASCII (0x0), 10 = nueva línea, etc.), y está disponible aquí . Sin embargo, no compite debido a los requisitos de desafío

Krzysztof Szewczyk
fuente
El golf de código se trata de dar respuestas cortas.
Alfe
2
@Alfe Malbolge es un lenguaje diseñado para ser extremadamente difícil de programar (enlace de Wikipedia) ; El hecho de que esto sea posible es bastante impresionante.
Giuseppe
44
Entonces, de hecho, esta es una respuesta corta. Solo se cambian los estándares. Ligeramente.
Alfe
3
@Alfe eres bienvenido para tratar de recortar algunos bytes! ;-)
Giuseppe
2

Python 3 , 118 bytes

r=range(9720)
for n in r[1:]:all(all(l%k+9//l for k in r[2:l])for l in(n%10**(i%5)//10**(i//5)for i in r))and print(n)

Pruébalo en línea!

Explicación

Advertencia: no hay cadenas reales involucradas en esta solución.

r=range(9720)
for n in r[1:]:                                        # For each positive integer up to 9720
 all( ... for l in(n%10**(i%5)//10**(i//5)for i in r)) # Check for all its substrings
  all(l%k ... for k in r[2:l])                         # If it is either prime
   +9//l                                               # Or smaller than 10
and print(n)                                           # Then print
Jitse
fuente
1

Rubí, 81 + 8 = 89 bytes

+8 bytes para -rprime.

puts (?1..?9*4).select{|m|(r=2..m.size).all?{|i|r.all?{|j|m[i-2,j].to_i.prime?}}}

Véalo en repl.it: https://repl.it/CniR/2

Jordán
fuente
1

Perl 6 ,  47 44  43 bytes

for 1..9719 {all(m:ex/..+/).Int.is-prime&&.say}
put grep {is-prime +all(m:ex/..+/):},1..9719
put grep {is-prime +all m:ex/..+/:},1..9719

Explicación:

# print the values space separated, with trailing newline
put

# that match
grep -> $_ {

  # call the method 「.is-prime」 ( that is what 「:」 is for )
  # (autothreaded)
  is-prime

  # convert following to numeric (autothreaded)
  +
  # a junction of
  all(
    # all substrings 2 characters or greater
    $_ ~~ m :exhaustive / . .+ /
  )

  # needed to indicate that 「is-prime」 is a method call
  :

},

# in this Range
1..9719
Brad Gilbert b2gills
fuente
1

C #, 261 249 247 bytes

Guardado 12 bytes gracias a Leaky Nun

()=>{Action<int>w=System.Console.WriteLine;int i=0,n,j,k,p,m,b;for(;++i<10001;){n=(i+"").Length;if(n<2)w(i);else{b=1;for(j=1;++j<=n;)for(k=0;k+j<=n;){p=int.Parse((i+"").Substring(k++,j));if(p%2<1)b=0;for(m=3;m<p;m+=2)if(p%m<1)b=0;}if(b>0)w(i);}}};

Esto compila a a Func<List<int>>.

La versión formateada se ve así:

() =>
{
    Action<int> w = System.Console.WriteLine;

    int i = 0, n, j, k, p, m, b;

    for (; ++i < 10001;)
    {
        n = (i + "").Length;

        if (n < 2)
            w(i);

        else
        {
            b = 1;
            for (j = 1; ++j <= n; )
                for (k = 0; k + j <= n; )
                {
                    p = int.Parse((i + "").Substring(k++, j));

                    if (p % 2 < 1)
                        b = 0;

                    for (m = 3; m < p; m += 2)
                        if (p % m < 1)
                            b = 0;
                }

            if (b > 0)
                w(i);
        }
    }
};
TheLethalCoder
fuente
Simplemente imprímalo directamente sin usar una lista
Leaky Nun
En lugar de falseo true, use 0>1y0<1
Leaky Nun
Puede consultar esto para obtener consejos de golf adicionales.
Leaky Nun
@LeakyNun Gracias por los consejos, generalmente me gusta publicar una versión de golf y luego pasar de allí.
TheLethalCoder
1

Swift 4 , 144 bytes

let p={n in !(2..<n).contains{n%$0<1}}
print((1...971).filter{$0<10||p($0)&&($0<100||p($0/10)&&p($0%100))}+[1373,3137,3797,6131,6173,6197,9719])

Pruébalo en línea!

Explicación

let p={n in !(2..<n).contains{n%$0<1}} // Helper function p, tests if a number is prime
print((1...971).filter{                // Print every number n in the range 1 to 971
 $0<10                                 //  that is less than 10
 ||p($0)&&                             //  or a prime and
 ($0<100                               //   is less than 100 or
  ||p($0/10)&&p($0%100))}              //   n/10 and n%100 are primes
+[1373,3137,3797,6131,6173,6197,9719]) // Print the four digit numbers
Herman L
fuente
1

JavaScript (Node.js) , 130 bytes

si yo puedo asumir pila infinita i*i<=n&&se puede quitar y i*i>nvueltas a i>=nlo que reduce el código de 9 bytes y tal vez convertir principal función recursiva a: https://tio.run/##LYpBDoIwEEX33AMyAxVbXUmccgX2xkWDRYeQaSPqyrvXkrj5ef/lze7j1vHJ8bWTcPMpTQRMWjm6XJFs0/DZ@EM/ASunBmCsKtfG9/rIiJ0rIoEoJpNbKXPdx@1jx5akGEiytqdNYp2nNFr / wR @ xHkD2Rn81dpLGIGtYfLuEO0yAmH4 (119 bytes)

_=>eval(`for(a=[i=1];++i<1e4;)P(i)&&a.push(i)`)||a
p=(n,i=1)=>i*i<=n&&n%++i?p(n,i):n%i
P=n=>n>9?p(n)*p(n%100)*p(n%1e3)*P(n/10|0):n

Pruébalo en línea!

DanielIndie
fuente
1

Malbolge , 1361 bytes

Versión simple y aburrida. Muestra números del más alto.

D'`r^"!=[YG3yUCvA-csNqp-nJ$HYFgDC#AbQ,|*)\rwvutm3kSonmlkdihg`&dc\aZ_X|V[ZYXQPt7SRQPOHGkKJIHG@d>=<A:98\}|:981U5.-2+0/.'K%$#G!E}e#z!~}v<]yxwpun4rkj0nmfN+ihaf_^$\a`_XW{>=YXWVONrLKPINGkE-IBAe(>=<;_?>=}|:3W1w543,P0).-&J*)(!E}|B"!~}|{zyr8potml2jongfkjibg`&d]\"`_XW{>=YXWVONr54JIHMFj-,HGF?>b%A@?87[;:981w543,P0).-&J*j(!EfeB"!~}_u;yrqpun4rqpihmlkjihg`&d]\"`_X|\[ZYXQuUNMLQJnH0LKJIBAe(>=<`#"8\<5Y9270T43,Pqp.-&J$)"!~D|#"y~}|u;s9qvotsrk1inglkdihg`&d]\"Z~XWVUZYXQu87SLKo2NGFjDIHGF?>bBA#"8\6;:981Uv.32+*)Mnm%$)('~D|{A!xwv{zyr8vXnsrkjoh.fNdchg`ed]#aC_^WVz=YXQPt7SRQPOHGkK-IHGF?>bBA#"8\6;:981Uv.32+*)Mnm%*#"F&%$#cy?}v<]\xwpun4rqSonmf,diha'eG]#a`_X|V[ZYXWPt76LKoIHGLEiCHGFED=aA:?>7[;:981w/4-,PO)o'&J*j(!E%edz@~}_u;yxqpo5mrqpoh.f,jibgf_%]\[!_XW{[ZYXQu87SLKo2NGFjJIHAF?c=BA@?>=<5Y38765.-Q10)o'&J*j(!E%e{z@~}|{ts9qpotsrk1oQglkd*)gIed]#DZ_^]VzZYRQuONMRKJnNGLEJCgG)(D=aA:?>=<;4X816/43,P0).-&+$H('gf|Bcb~w|u;yxwYutmrqj0nmleMib(fH%cba`_X|VUZYXWPt7SRQPOHGkEDIHG@dDC<;@?8\6|:32V0T43,+O)o'&J*)('&}C{"yxwv<tyr8vun4Ukpoh.fN+c)gIed]#DZ_^]VzTSRWPtTSLQJnH0LKJIBAe(>=BA@987[;:381Uv.32+*)Mnm%$)('~D${"y?}_uzyxqpo5srqSonmf,jihgfeG]#a`_X|V[ZYXWPt76LKo2NGFjJIH*)ED=a;@?>76;4X816/43,P*).',%I)('~Ded"y~}|u;srqvo5mlqpih.fN+cba`&d]\aZ~^]VUZSwWPUTSLpJ2NGLEiCHGFED=a;:?>7<5YX876v43,+O).-,+$H('&feBz!x}v{zsr8punsrk1inglkdihg`&d]\"Z~X]V[ZSwQVUTMRKo2NGFjDIHGF?>b%A@?87[;{921U5.3210)M-,%k#(!EfeB"y~}v{zyr8%

Pruébalo en línea!

Krzysztof Szewczyk
fuente
0

TI-83/84 BASIC, 124 Bytes

For(A,1,E4
DelVar Nint(log(A→P
Ans→Q
While Ans
For(I,0,Q-Ans
10^(P+1
AnsfPart(iPart(A/10^I)/Ans→S
min(Ans={2,3,5
If S≥7 and fPart(.5S
min(remainder(S,3+2cumSum(not(binompdf(int(.5√(S)),0
N+not(Ans→N
End
P-1→P
End
If not(N
Disp A
End

Recorre los primeros 10k enteros. Configura un contador en N para verificar cada primo de subcadena, e int (log (A recupera uno menos que el número de dígitos en el número actual. Luego colocamos ese número a un lado en una segunda variable para que podamos bajar P a través de cada longitud subcadena de al menos 2 dígitos. 10 ^ ... y AnsfPart (iPart (,,, genera la subcadena actual para verificar la primalidad, luego las siguientes 3 líneas hacen la verificación de primalidad a 1 o 0 en Ans. Si la subcadena no es primo , incrementamos N, y después de verificar todas las subcadenas si N sigue siendo 0, imprimimos el número actual.

¿Posiblemente se podrían hacer algunos ajustes para aumentar la eficiencia de la verificación de primalidades para esta prueba? ¡Me alegra haber encontrado un algoritmo en menos bytes que almacenar la salida directamente en el formato TI-83!

TiKevin83
fuente
0

Python 3.8 (prelanzamiento) , 194 bytes

r=range
s=str
l=lambda _:len(s(_))
[*map(print,[t for t in r(1,10**4) if all(all(int(x)%b for b in r(2,int(x))) for x in [s(t)[i:j+1] for i in r(l(t)) for j in r(i,l(t)) if l(s(t)[i:j+1])>1])])]

Pruébalo en línea!

jaaq
fuente
0

PHP , 135 bytes

for(;++$n<1e4;$p||print"$n
")for($p=$i=0;$i<$l=strlen($n);$i++)for($j=1;$j++<$l-$i;$p|=$k)for($k=($m=substr($n,$i,$j))-1;$k&&$m%$k--;);

Pruébalo en línea!

for(;                         // level 1 loop on
  ++$n<1e4;                   // all numbers from 1 to 10,000, $n is current number
  $p||print"$n\n"             // at the end of loop for each number, print $n if all multi digit sub strings were prime ($p=0)
)
  for(                        // level 2 loop on each digit of $n
    $p=                       // $p is a flag for all sub string primes and is set to 0 for each new $n
      $i=0;                   // $i is position of current digit (and sub string start position)
    $i<$l=strlen($n);         // $l is the total digits count in $n
    $i++                      // increment $i by one
  )
    for(                      // level 3 loop to create sub strings
      $j=1;                   // $j is length of sub string, we only care about multi digit sub strings so it starts from 1
      $j++<$l-$i;             // continue the loop as long as $j has not reached last digit and increment it by one
      $p|=$k                  // THIS IS RUN AFTER LOOP LEVEL 4: update $p flag based on value of $k
                              //     $p will be left at 0 only if all of the sub strings are prime (if $k is always 0)
    )
      for(                    // level 4 loop to check each sub string to be prime
        $k=(                  // $k is set to current sub string minus 1
          $m=substr($n,$i,$j) // $m is current sub string
        )-1;                  // 
        $k && $m%$k--;        // as long as $k is more than 0 and $m%$k is not zero, decrement $k by one and continue
                              //     a prime number will only get a 0 remainder, when $k gets to 1
                              //     so $k will be 0 for primes and more than 0 for non-primes
      );
Noche2
fuente