¡Haz algunos cuadrados principales!

17

¿Qué es un primer cuadrado?

Un primer cuadrado es un cuadrado donde los cuatro bordes son números primos diferentes.
Pero cuales?
¿Y cómo los construimos?

Aquí hay un ejemplo de un 4x4 Prime Square

1009  
0  0     
3  0   
1021    

Primero comenzamos desde la esquina superior izquierda. Estamos trabajando en sentido horario .
Elegimos el número primo más pequeño que tiene 4dígitos, que es 1009 .

Luego, necesitamos que el número primo más pequeño tenga 4dígitos, que comienza con a 9. Esto es 9001

El tercer número primo (4 dígitos) debe tener 1como último dígito (porque 9001 termina con 1)
y también debe ser el primo más pequeño de 4 dígitos con esta propiedad que no se haya usado antes como borde .
Este numero primo es 1021

El cuarto número primo debe tener 4dígitos, comenzar con a 1(porque 1009 comienza con a 1) y terminar con a 1(porque 1021 comienza con a 1)
El número primo más pequeño de 4 dígitos con esta propiedad que no se ha utilizado antes como borde es 1031

Tu tarea

Se le dará un número entero nde 3 to 100
Este número serán las dimensiones del n x ncuadrado.
Luego debe generar este cuadrado exactamente en la forma de los siguientes casos de prueba

Casos de prueba

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
  • La entrada y salida se pueden dar por cualquier método conveniente .
  • Puede imprimirlo en STDOUT o devolverlo como resultado de una función.
  • Un programa completo o una función son aceptables.
  • Cualquier cantidad de espacio en blanco extraño es aceptable, siempre que los números se alineen adecuadamente
  • Las lagunas estándar están prohibidas.
  • Este es el por lo que se aplican todas las reglas habituales de golf, y gana el código más corto (en bytes).

EDITAR
Esto es posible para todos n
Aquí están los primos paran=100

1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000289        
9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000091            
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000711             
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002191     



Y para aquellos de ustedes que no creen que esto sea posible, aquí están TODOS los casos de prueba

J42161217
fuente
Si n puede llegar a 100, podría ser bueno tener algunos casos de prueba más grandes que n = 10.
gastropner
44
¿Es comprobable que esto es posible para todos n: P? No es un problema con el desafío, solo curiosidad.
Urna de pulpo mágico
2
@MagicOctopusUrn Definitivamente no es posible para todos n: para n= 1, no podemos satisfacer la restricción de que los cuatro bordes son primos diferentes, mientras que para n= 2, nos vemos obligados a elegir 11,13,23, en cuyo punto el borde final es 12 que es compuesto. No tengo una prueba de que sea posible para todos n> 2, pero me sorprendería saber lo contrario: informalmente, cuantos más dígitos haya, más "margen de maniobra" habrá para satisfacer las restricciones.
Daniel Wagner
pagk+1pagkk463norte4 4
2
@MagicOctopusUrn El teorema del número primo para progresiones aritméticas dice algo bastante fuerte sobre la densidad de los números primos que terminan en 1, 3, 7 y 9 (en la notación allí, tome n = 10, a = 1/3/7/9 ); para lo suficientemente grande nhay al menos dos números primos de longitud que ncomienzan con 1 y terminan con cada uno de esos dígitos (por lo tanto, podemos elegir un borde inferior) y hay al menos tres números primos que comienzan con 1 y terminan con 1 (por lo tanto, podemos elegir un borde izquierdo).
Daniel Wagner

Respuestas:

4

05AB1E , 64 63 56 53 48 46 bytes

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

-1 byte gracias a @ Mr.Xcoder
-5 bytes gracias a @Grimy .

norte>4 4norte>7 7

Explicación:

°                 # 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)

Ver este consejo 05AB1E mío (sección Cómo comprimir grandes números enteros? ) Para entender por qué Ž9¦es 2460. Y vea esta sugerencia 05AB1E mía para comprender cómo se genera el cuadrado con el Λlienzo incorporado.

NĀiR}¦I¯JŽ9¦SΛn=4[1009,9001,1021,1031][1009,"001","201","301"]Λ
unI
si¯J"1009001201301"n=4
CŽ9¦S[2,4,6,0][→,↓,←,↑]

Kevin Cruijssen
fuente
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Λ
Grimmy
@ Grimy Gracias! Muy buenos campos de golf. He podido guardar 2 bytes más en función de su versión de 48 bytes al cambiar ÐθsXÅ?‚sXÅ¿ªa θyXÅ?yXÅ¿). Sin )embargo, no estoy exactamente seguro de por qué funciona dentro del alcance del bucle, ya que habría esperado que envolviera la lista principal también en su lista en la primera iteración. Pero incluso sin eso, el uso de en yylugar de Ðssaún ahorra 1 byte. :)
Kevin Cruijssen
4

05AB1E , 35 33 32 31 bytes

-1 byte gracias a Kevin Cruijssen

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

Pruébalo en línea!

Explicación:

°                 # 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
Mugriento
fuente
Esto se basa parcialmente en la respuesta de Kevin , pero en este punto es lo suficientemente diferente como para sentir que merecía su propia respuesta en lugar de un comentario.
Grimmy
1
Solo ahora veo esta respuesta. ¡Muy agradable! Además del método general (y, por lo tanto, la primera y la última parte), la determinación de los cuatro números primos y la construcción de la cadena se realiza de manera tan diferente que puedo entender la respuesta separada. +1 de mi parte Por cierto, puede guardar un byte eliminando el Θat . Solo 1es veraz en 05AB1E, así if Ny if N == 1son lo mismo.
Kevin Cruijssen
1
@KevinCruijssen ¡Gracias! Por supuesto que lo sabía, pero olvidé usarlo. En retrospectiva, Θies el equivalente 05AB1E de if (cond == true)...
Grimmy
Sí, eso es correcto. :) Θaún puede ser útil si desea convertir todo excepto 1a 0. Pero para la declaración if i, no es realmente necesario, al igual que con su pseudocódigo == true.
Kevin Cruijssen
2

JavaScript (ES8),  205 ... 185 177  173 bytes

norte>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`
`)

Pruébalo en línea!

¿Cómo?

Paso # 1: calcular los 4 primos

[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()

Paso # 2: formateando la salida

[...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
Arnauld
fuente
2

Jalea , 89 82 bytes

1ịÆn⁺f®$¿
’⁵*;Æn$©µDṪṪ×ḢÇ©;@©µ;Ç⁺;0ị®¤%⁵n/Ɗ¿$$©;Ç⁺%⁵’$¿$$µŒœṪDZUḊṖj€⁶x³¤ḊḊ¤;@Ḣ;2ị$

Pruébalo en línea!

Definitivamente podría ser más golfista, pero funciona eficientemente para grandes números.

Nick Kennedy
fuente
2

Jalea , 59 bytes

DṪṪ=DZḢṪṪ3ƭƊ}Tịḟ@Ḣ
’;⁸⁵*æR/µḢ;ç¥⁺⁺µŒœṪDZUḊṖj€⁶x³¤ḊḊ¤;@Ḣ;2ị$

Pruébalo en línea!

Respuesta de Jelly más corta pero mucho menos eficiente.

Nick Kennedy
fuente
1

JavaScript, 484 bytes

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]}

La última función sin nombre devuelve el arte ASCII.

Código original

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];
}

Complejidad de tiempo mejor y promedio: Ω (100 n n) en la notación de omega grande de Knuth (n pasos para restar n números de dígitos, 10 n sustracciones por verificación de divisibilidad, 10 n verificación de divisibilidad para verificación primaria, y Ω (1) verificaciones principales realizadas )

La peor complejidad en el tiempo: Ω (1000 n n) en la notación big-omega de Knuth (n pasos para restar n números de dígitos, 10 n sustracciones por verificación de divisibilidad, 10 n verificación de divisibilidad para verificación primaria y 10 n verificaciones principales realizadas).

Sospecho que n=100toma alrededor de 10 203 cálculos.

Nota al margen: Validé la sintaxis usando UglifyJS 3, y funcionó mucho mejor que yo, ahorrando un 47.13% más y ganando 282 bytes. Sin embargo, decidí no hacer de eso mi puntaje ya que siento que es una trampa.

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))));

Simplemente eliminó la última función ya que nunca se usan. En realidad, empeoró si se asignó y no se eliminó, incluido el código adicional que agregué.

Naruyoko
fuente
3
Esto parece incompleto? ¿Y no golf?
connectyourcharger
Si. Terminado / golf.
Naruyoko