Multiplicar o dividir por n

Nov 26 2020

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

15 JonathanAllan Nov 26 2020 at 01:35

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×:<?\
14 Lyxal Nov 26 2020 at 06:16

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)

Pruébalo desde cero

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

13 RobinRyder Nov 26 2020 at 05:21

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.

¡Pruébelo en línea!

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.

¡Pruébelo en línea!

11 Noodle9 Nov 26 2020 at 01:51

Python 2 , 47 43 39 bytes

Guardado 4 bytes gracias a xnor !!!
4 bytes guardados gracias a Neil !!!

r=i=1
while 1:r=r/i or r*i;print r;i+=1

¡Pruébelo en línea!

Impresiones \$\{a(n)\mid n \in \mathbb{N}\}\$ como una secuencia infinita.

10 RobinRyder Nov 26 2020 at 00:55

R , 43 39 bytes

-4 bytes gracias a Giuseppe.

for(i in 1:scan())T=T%/%i^(2*(i<T)-1);T

¡Pruébelo en línea!

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.

8 user Nov 26 2020 at 00:20

APL (Dyalog Unicode) , 18 bytes (SBCS)

{⍺>⍵:⍺×⍵⋄⌊⍵÷⍺}/⌽ö⍳

¡Pruébelo en línea!

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

(⌊⊢×⊣*∘×-)/⌽ö⍳

¡Pruébelo en línea!

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
8 AZTECCO Nov 26 2020 at 06:11

Haskell , 40 bytes

a#n|n>a=a*n|1>0=a`div`n
a=scanl1(#)[1..]

¡Pruébelo en línea!

  • 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.

7 DominicvanEssen Nov 26 2020 at 03:00

R , 41 bytes

for(m in 1:scan())T=`if`(m>T,T*m,T%/%m);T

¡Pruébelo en línea!

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 ...

7 ErikF Nov 26 2020 at 08:42

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

¡Pruébelo en línea!

7 Razetime Nov 26 2020 at 10:53

Adelante (gforth) , 82 bytes

: f 2dup 2dup > if * else swap / then dup . swap drop swap 1+ swap recurse ;
1 1 f

¡Pruébelo en línea!

Produce una secuencia infinita, separada por espacios.

7 NahuelFouilleul Nov 26 2020 at 00:02

Perl 5 -Minteger -061 , 36 , 27 bytes

-9 bytes gracias a @Abigail y @Sisyphus.

genera una secuencia infinita

say$/while$/=$//++$i||$/*$i

¡Pruébelo en línea!

7 JonathanAllan Nov 26 2020 at 02:15

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.

¡Pruébelo en línea!


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)
6 Arnauld Nov 26 2020 at 00:12

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

¡Pruébelo en línea!

6 Bubbler Nov 26 2020 at 13:49

Factor , 45 bytes

[ [1,b] 1 [ 2dup < [ * ] [ /i ] if ] reduce ]

¡Pruébelo en línea!

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
]
5 DominicvanEssen Nov 26 2020 at 03:33

Cáscara , 11 bytes

Fμ?*`÷<¹³)ḣ

¡Pruébelo en línea!

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
5 Xcali Nov 26 2020 at 04:51

Perl 5 -Minteger -p , 35 bytes

map$.=$_>$.?$.*$_:$./$_,2..$_;$_=$.

¡Pruébelo en línea!

Toma ncomo entrada e imprime el nthelemento de la lista.

5 ovs Nov 26 2020 at 04:58

05AB1E , 12 10 bytes

Imprime la secuencia infinita.

λN>₁N›i÷ë*

¡Pruébelo en línea!

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
5 coltim Nov 26 2020 at 03:27

K (OK) , 22 20 bytes

{_x*(1%y;y)y>x}/1+!:

¡Pruébelo en línea!

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.

5 reffu Nov 27 2020 at 22:44

Adelante (gforth) , 51 bytes

: f 1+ 1 tuck ?do i 2dup <= if * else / then loop ;

¡Pruébelo en línea!

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
5 DMiddendorf Nov 30 2020 at 22:45

Java (JDK) , 52 bytes

n->{int i,a=i=1;for(;i++<n;)a=i>a?i*a:a/i;return a;}

¡Pruébelo en línea!

Nota: Gracias @RedwolfPrograms por -1 Byte y @user por -10 (?) Bytes.

4 cairdcoinheringaahing Nov 26 2020 at 00:39

Gelatina , 11 bytes

1’ß×:>@?$Ị?

¡Pruébelo en línea!

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)
4 UnrelatedString Nov 26 2020 at 01:56

Brachylog , 10 bytes

⟦₁{÷ℕ₁|×}ˡ

¡Pruébelo en línea!

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.
4 Giuseppe Nov 26 2020 at 02:07

Gaia , 9 bytes

┅⟪<₌×/?⟫⊢

¡Pruébelo en línea!

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
4 Neil Nov 26 2020 at 03:00

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.

4 640KB Nov 26 2020 at 03:19

PHP , 57 bytes

function a($n){return$n?($n>$x=a($n-1))?$x*$n:$x/$n|0:1;}

¡Pruébelo en línea!

4 Stephen Nov 26 2020 at 03:32

cQuents , 14 bytes

=1:$>Z?$Z:Z_/$

¡Pruébelo en línea!

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
4 GalenIvanov Nov 26 2020 at 15:19

Raqueta , 66 bytes

(λ(n)(foldl(λ(x y)((if(< y x)* quotient)y x))1(range 1(+ 1 n))))

¡Pruébelo en línea!

4 J42161217 Nov 26 2020 at 03:40

Wolfram Language (Mathematica) , 40 bytes

a@1=1;a@n_:=If[#<n,n#,⌊#/n⌋]&@a[n-1]

¡Pruébelo en línea!

-2 bytes de @att

4 GalenIvanov Nov 26 2020 at 18:39

J , 21 bytes

[:(]<.@*[^*@-)/1+i.@-

¡Pruébelo en línea!

Un puerto J de la solución APL de @user : ¡no olvide votarlo!

4 KevinCruijssen Nov 27 2020 at 15:51

MathGolf , 11 9 bytes

1k{î`<¿*/

-2 bytes gracias a @ovs .

Emite el \$n^{th}\$ valor.

Pruébelo en línea.

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)