Residuo Palindrómico


25

Hoy, mientras escribo esto, es el 31 de marzo. En los Estados Unidos, esto es 3/31. Estaba jugando con 331un número para presentar un desafío, y descubrí que sus residuos (módulo de números pequeños) son palindrómicos. 331%2=1, 331%3=1, 331%4=3, 331%5=1, 331%6=1( 11311)

Su desafío aquí es, cuando se le da un número entero n > 2, generar los primeros nnúmeros positivos que tienen residuos palindrómicos cuando se toman el módulo [2,n].

Por ejemplo, para la entrada 7, la salida debería ser 1, 42, 43, 140, 182, 420, 421. Aquí está la tabla que explica por qué ese es el caso:

        mod
num | 2 3 4 5 6 7
-----------------
  1 | 1 1 1 1 1 1
 42 | 0 0 2 2 0 0
 43 | 1 1 3 3 1 1
140 | 0 2 0 0 2 0
182 | 0 2 2 2 2 0
420 | 0 0 0 0 0 0
421 | 1 1 1 1 1 1

Entrada

Un solo entero positivo ncon n > 2 cualquier formato conveniente .

Salida

La matriz / lista resultante de los primeros nresiduos palindrómicos, como se describe anteriormente. De nuevo, en cualquier formato adecuado.

Reglas

  • Para n > 10, suponga que la lista de residuos se aplana antes de verificar si es un palíndromo. Es decir, [1, 10, 11]es palindrómico, pero [1, 10, 1]no lo es.
  • Un programa completo o una función son aceptables. Si es una función, puede devolver el resultado en lugar de imprimirlo.
  • Si es posible, incluya un enlace a un entorno de prueba en línea para que otras personas puedan probar su código.
  • 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).

Ejemplos

[input]
[output]

3
[1, 6, 7]

4
[1, 4, 5, 8]

5
[1, 50, 60, 61, 110]

6
[1, 30, 31, 60, 61, 90]

7
[1, 42, 43, 140, 182, 420, 421]

8
[1, 168, 169, 336, 337, 504, 505, 672]

9
[1, 2520, 2521, 5040, 5041, 7560, 7561, 10080, 10081]

10
[1, 280, 281, 560, 1611, 1890, 1891, 2170, 2171, 2241]

11
[1, 22682, 27720, 27721, 50402, 55440, 55441, 78122, 83160, 83161, 105842]

¿Se supone que se debe ordenar la salida?
Arnauld

@Arnauld No es necesario que sea, no, siempre que incluya solo los primeros nelementos.
AdmBorkBork

2
arrgh ... tu desafío = tus reglas, pero " [1, 10, 11]es palindrómico, pero [1, 10, 1]no lo es" parece matemáticamente incorrecto.
Greg Martin

1
@ GregMartin Palíndromos fibrosos, no palíndromos de mathy. ;-)
AdmBorkBork

1
grr. Todo el fibroso palindrome en lugar de mathy palindrome lo hace mil veces más difícil en ciertos idiomas. Oh bien.
MildlyMilquetoast

Respuestas:


9

Haskell, 57 bytes

f n=take n[x|x<-[1..],(==)=<<reverse$show.mod x=<<[2..n]]

Ejemplo de uso: f 4-> [1,4,5,8]. Pruébalo en línea!

El primero =<<está en el contexto de la función y se traduce a lambda \x -> reverse x == xy el segundo =<<está en el contexto de la lista y es equivalente a concatMap, por ejemplo, map-and-flatten-one-list-level.


5

05AB1E , 12 bytes

µN2¹Ÿ%JÂQD½–

Pruébalo en línea!

Explicación

µ              # until counter equals input do:
 N             # push current iterations number
     %         # modulus each in
  2¹Ÿ          # range [2 ... input]
      J        # joined to string
       ÂQ      # equals it's reverse
         D     # duplicate
          ½    # if true, increase counter
           –   # if true print iteration number

¿Publicas respuestas 05AB1E desde tu teléfono? Porque haces estos rápidos jajaja.
Magic Octopus Urn

@carusocomputing: Muy rara vez, ya que muchos de los caracteres en cp-1252 son molestos para escribir / copiar y pegar en el teléfono. Este apareció justo antes de que revisara mi computadora después de la cena, así que tuve un buen momento :)
Emigna

4

Mathematica, 79 bytes

NestList[#+1//.x_/;!PalindromeQ[ToString/@Mod[x,Range@n+1]<>""]:>x+1&,1,n=#-1]&

4

JavaScript (ES6), 104 bytes

f=(n,x=(k=--n,2))=>k?([...Array(n)].map(_=>(r=x%++i+r,x%i),i=1,r='').join``==r?k--&&x+' ':'')+f(n,x+1):1

Manifestación

Nota : debido a las numerosas llamadas recursivas, esto se bloqueará para n> 8 en Firefox o n> 10 en Chrome.



3

MATL , 19 bytes

Gracias a @AdmBorkBork por señalar un error en una versión anterior del código, ahora corregido

`@Gq:Q\VXztP=?@]NG<

Pruébalo en línea!

Explicación

`        % Do...while
  @      %   Push iteration index, starting at 1
  Gq:Q   %   Push [2 3 ... n], where n is the input
  \      %   Modulo, element-wise
  V      %   Convert to string. Numbers are separated by spaces
  Xz     %   Remove spaces
  tP     %   Duplicate, flip
  =      %   Equal? (element-wise)
  ?      %   If all results were true
    @    %     Push current iteration index. It is one of the sought numbers
  ]      %   End
  N      %   Push number of elements in stack
  G      %   Push input n
  <      %   Less than? This is the loop condition
         % End (implicit). Display (implicit)

3

Scala, 90 86 82 bytes

(n:Int)=>Stream.from(1)filter{i=>val d=(2 to n)map(i%)mkString;d.reverse==d}take(n)

Explicación

Stream.from(1)                              // From an infinite Stream starting from 1,
    filter ( i => {                         // keep only elements matching the next condition :
        val d=(2 to n)map(i%)mkString;      // Generate residues and convert to String,
        d.reverse==d                        // return true if palindrom, false otherwise
    })take(n)                               // Finally, take the n first elements matching the condition

Casos de prueba

val f = (n:Int)=>...    // assign function
(3 to 11).foreach { i =>
    println(i + "\n" + f(i).mkString(", ") + "\n")
}

Resultados

3
1, 6, 7

4
1, 4, 5, 8

5
1, 50, 60, 61, 110

6
1, 30, 31, 60, 61, 90

7
1, 42, 43, 140, 182, 420, 421

8
1, 168, 169, 336, 337, 504, 505, 672

9
1, 2520, 2521, 5040, 5041, 7560, 7561, 10080, 10081

10
1, 280, 281, 560, 1611, 1890, 1891, 2170, 2171, 2241

11
1, 22682, 27720, 27721, 50402, 55440, 55441, 78122, 83160, 83161, 105842

Ediciones

# 1 (90 => 86)

  • función anónima

# 2 (86 => 82)

  • eliminar caracteres de punto inútiles después del paréntesis o paréntesis (ej .: (2 to n).map(%i)=>(2 to n)map(%i)

1
Bienvenido a PPCG!
Martin Ender

¡Gracias! Me preguntaba si podría cambiar def f(n:Int)=a (n:Int)=>, ya que también define una función (pero sin nombre). ¡Ahorra 4 bytes!
norbjd

Sí, se permiten funciones sin nombre , siempre que no necesite el nombre para una llamada recursiva o algo así.
Martin Ender

Genial, editado :)
norbjd

2

Jalea , 12 bytes

%ЀḊDFŒḂ
1ç#

¿Cómo?

1ç# - Main link: n
1   - initialise "i" at 1
  # - increment i and yield a list of the first n truthful results of:
 ç  -     last link (1) as a dyad

%ЀḊDFŒḂ - Link 1, test a value "i" for mod [2,n] being palindromic: i, n
 Ѐ      - for each, mapped over the right argument, i.e. for j = 1 to n:
%        -     i modulo j
   Ḋ     - dequeue, i.e. discard the modulo 1 result
    D    - convert to decimal list (vectorises)
     F   - flatten into one list
      ŒḂ - is palindromic?

Pruébalo en línea!


1

CJam , 28 bytes

0ri:N{{)_N),2>f%s_W%#}g_p}*;

Pruébalo en línea!

Explicación

0          e# Push 0, the value we'll repeatedly increment to search for valid outputs.
ri:N       e# Read input, convert to integer, store in N.
{          e# Run this block N times...
  {        e#   Run this block until the condition is true, which will find the next
           e#   number with palindromic residues...
    )_     e#     Increment and duplicate.
    N),2>  e#     Push [2 3 ... N].
    f%     e#     Take the current value modulo each of these.
    s      e#     Flatten them into a single string.
    _W%    e#     Duplicate and reverse.
    #      e#     Try to find the reverse in the original. A common way to compute
           e#     "not equal" for strings of the same length.
  }g
  _p       e#   Print a copy of the result.
}*
;          e# Discard the final result to prevent printing it twice.

1

PHP, 93 bytes

for(;$x<$a=$argn;$s="")for($i=1,++$n;$i++<$a;)if($i==$a&strrev($s.=$n%$i)==$s)echo$n._.!++$x;

Salida de bucles de versión 2 en línea como cadena

Expandido

for(;$x<$a=$argn;$s="") 
for($i=1,++$n;$i++<$a;)
    if($i==$a&strrev($s.=$n%$i)==$s)echo$n._.!++$x; 

PHP 130 bytes

for(;count($r)<$a=$argn;$s=[])for($i=1,++$n;$i++<$a;){$s[]=$n%$i;if(count($s)==$a-1&strrev($j=join($s))==$j)$r[]=$n; }print_r($r);

Versión en línea 2 Loops

Expandido

for(;count($r)<$a=$argn;$s=[])
for($i=1,++$n;$i++<$a;){
    $s[]=$n%$i;
    if(count($s)==$a-1&strrev($j=join($s))==$j)$r[]=$n; 
}
print_r($r);

PHP, 139 bytes con 1 bucle

for($i=$n=1;count($r)<($a=$argn)&$i++<$a;){$s[]=$n%$i;if(count($s)==$a-1){if(strrev($j=join($s))==$j)$r[]=$n;$n++;$s=[];$i=1;}}print_r($r);

Versión en línea 1 Loop

Corre con

echo '<string>' | php -nR '<code>'

Expandido

for($i=$n=1;count($r)<($a=$argn)&$i++<$a;){
    $s[]=$n%$i;
    if(count($s)==$a-1){
        if(strrev($j=join($s))==$j)$r[]=$n;
        $n++;
        $s=[];
        $i=1;
    }
}
print_r($r);

1

QBIC , 48 bytes

:{A=G[2,a|A=A+!q%b$]~A=_fA||h=h+1?q]q=q+1~h=a|_X

Beats Mathematica! Ejecución de muestra:

Command line: 10
 1 
 280 
 281 
 560 
 1611 
 1890 
 1891 
 2170 
 2171 
 2241 

Explicación:

:{          Get 'a' from the command line, start an inf. loop
A=G         Clear out whatever's in A$
[2,a|       For each of the numbers we want to modulo
A=A+        Add to A$ 
     q%b       our current number MODULO te loop iterator
    !   $      cast to string
]           NEXT
~A=_fA|     If the string of remainders is a palindrome (_f ... | is Reverse())
|h=h+1      THEN h=h+1 (h starts at 0) - this counts how many hits we've had
 ?q            also, print the number with the palindromic remainder
]           END IF
q=q+1       Test the next number
~h=a|_X     If we've had 'a' hits, quit.
            The last IF and the infinite loop are closed implicitly.

1

Japt , 26 bytes

L³o fR{C=Uò2@R%Xì ¥CwÃj1U

Pruébalo en línea! Toma unos segundos en todos entradas, así que sea paciente, por favor.

Esto sería considerablemente más corto (y más rápido) si hubiera una función integrada para obtener los primeros N números que satisfagan alguna condición:

R{C=Uò2@R%Xì ¥Cw}aU
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.