Multiplicar o dividir por n
Aquí hay un desafío simple, por lo que esperamos que muchos idiomas puedan participar.
Dado un entero positivo \$n\$, salida \$A076039(n)\$de la OEIS .
Es decir, comience con \$a(1)=1\$. Entonces para \$n>1\$:
$$a(n)=\left\{ \begin{array}{ll} n\cdot a(n-1), & \text{if } n>a(n-1) \\ \lfloor a(n-1)/n \rfloor, & \text{otherwise.}\end{array} \\ \right. $$
Casos de prueba:
1 -> 1
2 -> 2 (2 > 1, so multiply)
3 -> 6 (3 > 2, so multiply)
4 -> 1 (4 < 6, so divide and take the integer part)
5 -> 5
6 -> 30
17 -> 221
99 -> 12
314 -> 26
Se pueden encontrar más casos de prueba en la página de OEIS.
Según las reglas de secuencia habituales , puede ingresar y generar resultados de una manera generalmente aceptada: indexación basada en 1 o 0, generar una secuencia infinita, generar el primer \$n\$valores, genere solo el \$n^\text{th}\$ valor, y así sucesivamente, pero especifíquelo en su respuesta.
Esto es code-golf , ¡así que gana el código más corto en bytes en cada idioma!
Respuestas
Gelatina , 6 bytes
R×:<?/
Un enlace monádico que acepta un número entero positivo, \$n\$, que da un número entero positivo, \$a(n)\$.
¡Pruébelo en línea! O vea la suite de pruebas .
¿Cómo?
R×:<?/ - Link:
R - range -> [1..n]
/ - reduce by (i.e. evaluate f(f(...f(f(f(1,2),3),4),...),n) with this f(a,b):
? - if...
< - ...condition: (a) less than (b)?
× - ...then: multiply -> a×b
: - ...else: integer divide -> a//b
Salida de la secuencia hasta \$a(n)\$ con:
R×:<?\
Scratch 3.0, 29 27 bloques / 234 167 bytes
Como SB Syntax:
define f(n)
if<(n)=(1)>then
add(1)to[v v
else
f((n)-(1
set[d v]to(item(length of[v v])of[v v
if<(n)>(d)>then
add((n)*(d))to[v v
else
add([floor v] of ((n)/(d)))to[v v]
end
end
when gf clicked
delete all of [v v
ask()and wait
f(answer)
No estoy seguro de algunos métodos de entrada / salida, así que pensé que estaría seguro y lo convertiría en un programa completo con una función auxiliar.
Responder a esto permitió que mi cuenta se promoviera de "nueva" a "estándar", por lo que siempre es divertido.
-67 bytes gracias a @att
Lenguaje de programación Shakespeare , 221 bytes
,.Ajax,.Puck,.
Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:You cat.
Scene V:.
Puck:You is the sum ofYou a cat.
Ajax:Open heart.Is I nicer you?If notYou is the quotient betweenyou I.
If soYou is the product ofyou I.Let usScene V.
Produce la lista infinita. Sin embargo, tenga en cuenta que no hay un separador entre los valores de salida, por lo que la salida es algo difícil de leer.
Mi mejor intento de agregar un separador (un byte nulo) se reduce como
Lenguaje de programación Shakespeare , 297 bytes
,.Ajax,.Puck,.Page,.
Act I:.Scene I:.
[Enter Ajax and Puck]
Ajax:You cat.
Scene V:.[Exit Puck][Enter Page]
Ajax:Speak thy.
Page:You is the sum ofYou a cat.
Scene X:.[Exit Page][Enter Puck]
Ajax:Open heart.Is I nicer you?If notYou is the quotient betweenyou I.
If soYou is the product ofyou I.Let usScene V.
R , 43 39 bytes
-4 bytes gracias a Giuseppe.
for(i in 1:scan())T=T%/%i^(2*(i<T)-1);T
Emite el \$n\$th término, 1-indexado.
Inicializando la secuencia con \$a(0)=1\$también funciona, ya que la fórmula da \$a(1)=1\$como se desee. La variable Tse coacciona al número entero 1y aplicamos repetidamente una versión más compacta de la fórmula:
$$a(n)=\left\lfloor \frac{a(n-1)}{n^{2\mathbb{I_{n<a(n-1)}} -1}}\right\rfloor $$
(con \$\mathbb I\$la función de indicador). Esto cubre ambos casos de la definición original.
APL (Dyalog Unicode) , 18 bytes (SBCS)
{⍺>⍵:⍺×⍵⋄⌊⍵÷⍺}/⌽ö⍳
Una función que apenas se juega al golf pero que es segura y que genera el enésimo elemento de la secuencia.
APL (Dyalog Unicode) , 15 14 bytes (SBCS)
1 byte guardado gracias a @ Adám
(⌊⊢×⊣*∘×-)/⌽ö⍳
Da salida al enésimo elemento de la secuencia. Me acabo de dar cuenta de que esto no funcionará si \$n = a(n-1)\$porque eleva n al poder de \$n - a(n-1)\$y multiplica eso por \$a\$, aunque por lo que puedo decir , esta función funciona hasta al menos n = 2.000.000.
(⌊⊢×⊣*∘×-)/⌽ö⍳
⍳ ⍝ Make a range to n
⌽ö ⍝ Then reverse it and
(⌊⊢×⊣*∘×-)/ ⍝ reduce it with a train:
× ⍝ Multiply
⊢ ⍝ a(n-1) with
⊣ ⍝ n
*∘× ⍝ to the power of the sign of
- ⍝ n - a(n-1)
⌊ ⍝ Floor it
Haskell , 40 bytes
a#n|n>a=a*n|1>0=a`div`n
a=scanl1(#)[1..]
- Produce secuencia infinita.
El operador infijo # calcula el siguiente término, lo usamos para doblar todos los enteros positivos [1 ..] pero usando scanl1 en su lugar, que nos da todos los pasos.
R , 41 bytes
for(m in 1:scan())T=`if`(m>T,T*m,T%/%m);T
Me obligué a no mirar la respuesta R de Robin Ryder antes de intentarlo. Afortunadamente, se nos ocurrieron diferentes enfoques entre sí, aunque ambos parecen (hasta ahora) tener exactamente la misma longitud en bytes, lamentablemente para mí, el suyo ahora es 2 bytes más corto ...
C (gcc) , 35 bytes
Toma un índice de inicio basado en 1 y devuelve el enésimo valor de secuencia.
f(i,j){i=i?i>(j=f(i-1))?j*i:j/i:1;}
Adelante (gforth) , 82 bytes
: f 2dup 2dup > if * else swap / then dup . swap drop swap 1+ swap recurse ;
1 1 f
Produce una secuencia infinita, separada por espacios.
Perl 5 -Minteger -061 , 36 , 27 bytes
-9 bytes gracias a @Abigail y @Sisyphus.
genera una secuencia infinita
say$/while$/=$//++$i||$/*$i
Python 3.8+ , 45 39 bytes
-2 gracias a xnor ( while print(...)!=0:→ while[print(...)]:)
-4 gracias a Neil ( [a*n,a//n][a>n]→ a//n or a*n)
a=n=1
while[print(a:=a//n or a*n)]:n+=1
Un programa completo que imprime \$a(n)\$ para todos los números naturales.
Como función recursiva, 49:
f=lambda v,n=1,a=1:a*(v<n)or f(v,n+1,a//n or a*n)
JavaScript (Node.js) , 38 35 bytes
Guardado 3 bytes gracias a @Neil
Devuelve el \$n\$-ésimo término, 1-indexado.
f=(n,k=i=1n)=>i++<n?f(n,k/i||k*i):k
Factor , 45 bytes
[ [1,b] 1 [ 2dup < [ * ] [ /i ] if ] reduce ]
Reducción sencilla. Toma un índice basado en 1 y devuelve el enésimo término.
[ ! anonymous lambda
[1,b] 1 [ ... ] reduce ! reduce {1..n} by the following, starting with 1:
2dup < ! ( an n -- an n an<n)
[ * ] [ /i ] if ! ( a_n+1 ) multiply if an < n, int-divide otherwise
]
Cáscara , 11 bytes
Fμ?*`÷<¹³)ḣ
F # Fold a function over
ḣ # sequence from 1..input;
μ?*`÷<¹³) # function with 2 arguments:
? # if
<¹³ # arg 2 is smaller than arg 1
* # arg 1 times arg 2
`÷ # else arg 1 integer divided by arg 2
Perl 5 -Minteger -p , 35 bytes
map$.=$_>$.?$.*$_:$./$_,2..$_;$_=$.
Toma ncomo entrada e imprime el nthelemento de la lista.
05AB1E , 12 10 bytes
Imprime la secuencia infinita.
λN>₁N›i÷ë*
Comentó :
λ # infinite list generation
# implicitly push a(n-1) (initially 1)
N> # push n, since N is 0-indexed, this needs to be incremented
₁N› # is a(n-1) > n-1?
i÷ # if this is true, integer divide a(n-1) by n
ë* # else multiply a(n-1) and n
K (OK) , 22 20 bytes
{_x*(1%y;y)y>x}/1+!:
En lugar de usar $[y>x;y;1%y], indexa en la lista (1%y;y)usando la condición booleana y>xpara guardar un par de bytes.
Adelante (gforth) , 51 bytes
: f 1+ 1 tuck ?do i 2dup <= if * else / then loop ;
Explicación del código
: f \ start word definition
1+ \ add 1 to n
1 tuck \ set up accumulator and loop parameters
?do \ loop from 1 to n (if n > 1)
i 2dup \ set up top two stack values and duplicate
<= if \ if a(n-1) <= n
* \ multiply
else \ otherwise
/ \ divide
then \ end if
loop \ end loop
; \ end word definition
Java (JDK) , 52 bytes
n->{int i,a=i=1;for(;i++<n;)a=i>a?i*a:a/i;return a;}
Nota: Gracias @RedwolfPrograms por -1 Byte y @user por -10 (?) Bytes.
Gelatina , 11 bytes
1’ß×:>@?$Ị?
Cómo funciona
1’ß×:>@?$Ị? - Main link f(n). Takes n on the left
? - If statement:
Ị - If: n ≤ 1
1 - Then: Yield 1
$ - Else:
’ - n-1
ß - f(n-1)
? - If statement:
>@ - If: n > f(n-1)
× - Then: n × f(n-1)
: - Else: n : f(n-1)
Brachylog , 10 bytes
⟦₁{÷ℕ₁|×}ˡ
Da la lista de singleton en [1]lugar de 1n = 1, pero nada fuera de lo común de otra manera.
ˡ Reduce
⟦₁ 1 .. n
{ } by:
÷ integer division
ℕ₁ if the result is 1 or greater,
|× multiplication if not.
Gaia , 9 bytes
┅⟪<₌×/?⟫⊢
Básicamente lo mismo que la respuesta más corta de Jelly. 1-indexado, imprime a(n), aunque ⊢se puede intercambiar ⊣para obtener los primeros nelementos.
# implicit input n
┅ # push 1...n
⟪ ⟫⊢ # reduce the list by the following function:
<₌ # push an extra copy of a(i-1) and i and check if less than?
× ? # if true, then multiply
/ # else integer divide
# implicitly print top of stack
Retina , 58 bytes
K`_ _
"$+"+L$`(^_+|_)(?<=(\1)+) (\1)+
_$`$1 $#3*$#2*
r`_\G
¡Pruébelo en línea! No hay suite de prueba debido a la forma en que el script usa el historial Explicación:
K`_ _
Reemplace la entrada con un par de unos (en unario). El primero es el índice de bucle, mientras que el segundo es la salida.
"$+"+
nTiempos de bucle .
L$`(^_+|_)(?<=(\1)+) (\1)+
Divida tanto la salida como el índice de bucle por el índice de bucle, o por 1 si la división fuera cero.
_$`$1 $#3*$#2*
Incrementa el índice de bucle y multiplica los dos cocientes. Esto da como resultado output/index*index/indexo output/1*index/1respectivamente.
r`_\G
Convierta la salida final a decimal.
cQuents , 14 bytes
=1:$>Z?$Z:Z_/$
Explicación
=1 first term is 1
: mode sequence: given n, output nth term; otherwise, output indefinitely
each term equals:
$>Z? : if n > seq(n - 1) else
$Z n * seq(n - 1)
Z_/$ seq(n - 1) // n
Raqueta , 66 bytes
(λ(n)(foldl(λ(x y)((if(< y x)* quotient)y x))1(range 1(+ 1 n))))
MathGolf , 11 9 bytes
1k{î`<¿*/
-2 bytes gracias a @ovs .
Emite el \$n^{th}\$ valor.
Explicación:
1 # Push 1
k{ # Loop the input amount of times:
î # Push the 1-based loop index
` # Duplicate the top two items
<¿ # If the current value is smaller than the 1-based loop index: a(n-1)<n:
* # Multiply the value by the 1-based loop index
# Else:
/ # Integer-divide instead
# (after the loop, the entire stack joined together is output implicitly)