Moltiplicare o dividere per n
Questa è una semplice sfida, quindi si spera che molte lingue potranno partecipare.
Dato un numero intero positivo \$n\$, output \$A076039(n)\$dal OEIS .
Cioè, inizia con \$a(1)=1\$. Quindi per \$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. $$
Casi test:
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
Altri casi di test possono essere trovati sulla pagina OEIS.
In base alle normali regole di sequenza , puoi inserire e produrre in un modo generalmente accettato: indicizzazione basata su 1 o 0, output di una sequenza infinita, output del primo \$n\$valori, restituisce solo \$n^\text{th}\$ valore e così via, ma specificalo nella tua risposta.
Questo è il codice del golf , quindi il codice più breve in byte in ogni lingua vince!
Risposte
Gelatina , 6 byte
R×:<?/
Un collegamento monadico che accetta un numero intero positivo, \$n\$, che restituisce un numero intero positivo, \$a(n)\$.
Provalo online! Oppure guarda la suite di test .
Come?
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
Emette la sequenza fino a \$a(n)\$ con:
R×:<?\
Scratch 3.0, 29 27 blocchi / 234 167 byte
Come sintassi SB:
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)
Non sono sicuro di alcuni metodi di input / output, quindi ho pensato di essere al sicuro e di renderlo un programma completo con una funzione di supporto.
Rispondere a questo ha permesso al mio account di essere promosso da "nuovo" a "standard", quindi è sempre divertente.
-67 byte grazie a @att
Linguaggio di programmazione Shakespeare , 221 byte
,.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.
Emette l'elenco infinito. Si noti tuttavia che non esiste un separatore tra i valori di output, quindi l'output è piuttosto difficile da leggere.
Il mio miglior tentativo di aggiungere un separatore (un byte nullo) viene visualizzato come
Linguaggio di programmazione Shakespeare , 297 byte
,.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 byte
-4 byte grazie a Giuseppe.
for(i in 1:scan())T=T%/%i^(2*(i<T)-1);T
Emette il \$n\$esimo termine, 1-indicizzato.
Inizializzazione della sequenza con \$a(0)=1\$funziona anche, poiché la formula fornisce quindi \$a(1)=1\$come desiderato. La variabile Tviene forzata all'intero 1e applichiamo ripetutamente una versione più compatta della formula:
$$a(n)=\left\lfloor \frac{a(n-1)}{n^{2\mathbb{I_{n<a(n-1)}} -1}}\right\rfloor $$
(con \$\mathbb I\$la funzione indicatore). Questo copre entrambi i casi della definizione originale.
APL (Dyalog Unicode) , 18 byte (SBCS)
{⍺>⍵:⍺×⍵⋄⌊⍵÷⍺}/⌽ö⍳
Una funzione appena giocata ma sicura che emette l'ennesimo elemento della sequenza.
APL (Dyalog Unicode) , 15 14 byte (SBCS)
Salvato 1 byte grazie a @ Adám
(⌊⊢×⊣*∘×-)/⌽ö⍳
Emette l'ennesimo elemento della sequenza. Mi sono appena reso conto che non funzionerà se \$n = a(n-1)\$perché eleva n al potere di \$n - a(n-1)\$e lo moltiplica per \$a\$, sebbene per quanto ne so , questa funzione funziona almeno fino a 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 byte
a#n|n>a=a*n|1>0=a`div`n
a=scanl1(#)[1..]
- Emette una sequenza infinita.
L'operatore Infix # calcola il termine successivo, lo usiamo per piegare tutti i numeri interi positivi [1 ..] ma usando scanl1 invece che ci fornisce tutti i passaggi.
R , 41 byte
for(m in 1:scan())T=`if`(m>T,T*m,T%/%m);T
Mi sono costretto a non guardare la risposta R di Robin Ryder prima di provarci. Fortunatamente abbiamo trovato approcci diversi tra loro, anche se entrambi sembrano (finora) avere esattamente la stessa lunghezza in byte, purtroppo per me il suo ora è più corto di 2 byte ...
C (gcc) , 35 byte
Accetta un indice iniziale basato su 1 e restituisce l'ennesimo valore di sequenza.
f(i,j){i=i?i>(j=f(i-1))?j*i:j/i:1;}
Forth (gforth) , 82 byte
: f 2dup 2dup > if * else swap / then dup . swap drop swap 1+ swap recurse ;
1 1 f
Emette una sequenza infinita, separata da spazi.
Perl 5 -Minteger -061 , 36 , 27 byte
-9 byte grazie a @Abigail e @Sisyphus.
produce una sequenza infinita
say$/while$/=$//++$i||$/*$i
Python 3.8+ , 45 39 byte
-2 grazie a xnor ( while print(...)!=0:→ while[print(...)]:)
-4 grazie 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 programma completo che stampa \$a(n)\$ per tutti i numeri naturali.
Come funzione ricorsiva, 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 byte
Salvati 3 byte grazie a @Neil
Restituisce il \$n\$-esimo termine, 1-indicizzato.
f=(n,k=i=1n)=>i++<n?f(n,k/i||k*i):k
Fattore , 45 byte
[ [1,b] 1 [ 2dup < [ * ] [ /i ] if ] reduce ]
Riduzione diretta. Accetta un indice a base 1 e restituisce l'n-esimo termine.
[ ! 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
]
Husk , 11 byte
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 byte
map$.=$_>$.?$.*$_:$./$_,2..$_;$_=$.
Accetta ncome input e stampa l' nthelemento nell'elenco.
05AB1E , 12 10 byte
Stampa la sequenza infinita.
λN>₁N›i÷ë*
Commentato :
λ # 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 byte
{_x*(1%y;y)y>x}/1+!:
Anziché utilizzare $[y>x;y;1%y], indicizza l'elenco (1%y;y)utilizzando la condizione booleana y>xper salvare un paio di byte.
Forth (gforth) , 51 byte
: f 1+ 1 tuck ?do i 2dup <= if * else / then loop ;
Spiegazione del codice
: 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 byte
n->{int i,a=i=1;for(;i++<n;)a=i>a?i*a:a/i;return a;}
Nota: grazie a @RedwolfPrograms per -1 byte e @user per -10 (?) Byte.
Gelatina , 11 byte
1’ß×:>@?$Ị?
Come funziona
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 byte
⟦₁{÷ℕ₁|×}ˡ
Fornisce la lista singleton [1]invece di 1per n = 1, ma altrimenti niente fuori dall'ordinario.
ˡ Reduce
⟦₁ 1 .. n
{ } by:
÷ integer division
ℕ₁ if the result is 1 or greater,
|× multiplication if not.
Gaia , 9 byte
┅⟪<₌×/?⟫⊢
Fondamentalmente la stessa della risposta Jelly più breve. 1-indicizzato, stampe a(n), anche se ⊢potrebbe essere sostituito con ⊣per ottenere i primi nelementi.
# 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 byte
K`_ _
"$+"+L$`(^_+|_)(?<=(\1)+) (\1)+
_$`$1 $#3*$#2*
r`_\G
Provalo online! Nessuna suite di test a causa del modo in cui lo script utilizza la cronologia. Spiegazione:
K`_ _
Sostituisci l'input con una coppia di 1 (in unario). Il primo è l'indice del ciclo mentre il secondo è l'output.
"$+"+
nTempi di loop .
L$`(^_+|_)(?<=(\1)+) (\1)+
Dividi sia l'output che l'indice del loop per l'indice del loop o per 1 se la divisione è zero.
_$`$1 $#3*$#2*
Incrementa l'indice del ciclo e moltiplica insieme i due quozienti. Ciò si traduce in output/index*index/indexo output/1*index/1rispettivamente.
r`_\G
Converti l'output finale in decimale.
cQuents , 14 byte
=1:$>Z?$Z:Z_/$
Spiegazione
=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
Racchetta , 66 byte
(λ(n)(foldl(λ(x y)((if(< y x)* quotient)y x))1(range 1(+ 1 n))))
J , 21 byte
[:(]<.@*[^*@-)/1+i.@-
Una porta J della soluzione APL di @user : non dimenticare di votare!
MathGolf , 11 9 byte
1k{î`<¿*/
-2 byte grazie a @ovs .
Emette il \$n^{th}\$ valore.
Spiegazione:
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)