# Multiply or Divide by n

Here's a simple challenge, so hopefully lots of languages will be able to participate.

Given a positive integer $$\n\$$, output $$\A076039(n)\$$ from the OEIS.

That is, start with $$\a(1)=1\$$. Then for $$\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.$$

### Test cases:

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


More test cases can be found on the OEIS page.

Per usual rules, you can input and output in a generally accepted manner: 1- or 0-based indexing, output an infinite sequence, output the first $$\n\$$ values, output only the $$\n^\text{th}\$$ value, and so forth, but specify that in your answer.

This is , so shortest code in bytes in each language wins!

# Jelly, 6 bytes

R×:<?/


A monadic Link accepting a positive integer, $$\n\$$, which yields a positive integer, $$\a(n)\$$.

Try it online! Or see the test-suite.

### How?

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


Output the sequence up to $$\a(n)\$$ with:

R×:<?\

• ...I think I may have overcomplicated mine a bit – caird coinheringaahing Nov 25 '20 at 18:38
• Yeah, easily done but your solution is still nice IMO. – Jonathan Allan Nov 25 '20 at 18:42

# Scratch 3.0, 29 27 blocks/234 167 bytes

As SB Syntax:

define f(n)
if<(n)=(1)>then
else
f((n)-(1
set[d v]to(item(length of[v v])of[v v
if<(n)>(d)>then
else
end
end
when gf clicked
delete all of [v v


Try it on scratch

I'm a little unsure of some input/output methods, so I thought I'd be safe and just make it a full program with a helper function.

Answering this allowed my account to be promoted from "new" to "standard", so that's always fun.

-67 bytes thanks to @att

• This sounds like a really nice language - strongly, statically typed with few runtime errors; a specially designed editor; a nice way of handling parallel tasks; and great support for graphics. I totally need to learn this. – user Nov 25 '20 at 23:40
• 167 bytes – att Nov 26 '20 at 7:02
• @downvoter why? – lyxal Nov 28 '20 at 3:33

# Shakespeare Programming Language, 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.


Try it online!

Outputs the infinite list. Note however that there is no separator between the output values, so the output is somewhat difficult to read.

My best attempt at adding a separator (a null byte) comes down as

# Shakespeare Programming Language, 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.


Try it online!

# Python 2, 4743 39 bytes

Saved 4 bytes thanks to xnor!!!
Saved 4 bytes thanks to Neil!!!

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


Try it online!

Prints $$\\{a(n)\mid n \in \mathbb{N}\}\$$ as an infinite sequence.

• Looks like you can save bytes using a list for selection: Try it online! – xnor Nov 25 '20 at 20:54
• @xnor Nice one - thanks! :D – Noodle9 Nov 25 '20 at 21:12
• r=r/i or r*i saves 4 bytes. – Neil Nov 25 '20 at 21:14
• @Neil Sweet - thanks! :D – Noodle9 Nov 25 '20 at 21:18
• Why the downvote? Could whoever downvoted please explain and I'll try to fix it. – Noodle9 Nov 28 '20 at 9:58

# R, 43 39 bytes

-4 bytes thanks to Giuseppe.

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


Try it online!

Outputs the $$\n\$$th term, 1-indexed.

Initializing the sequence with $$\a(0)=1\$$ also works, as the formula then gives $$\a(1)=1\$$ as desired. The variable T is coerced to the integer 1, and we apply repeatedly a more compact version of the formula:

$$a(n)=\left\lfloor \frac{a(n-1)}{n^{2\mathbb{I_{n

(with $$\\mathbb I\$$ the indicator function). This covers both cases of the original definition.

• 41 bytes – Giuseppe Nov 25 '20 at 18:18
• @Giuseppe Very nice, thanks! – Robin Ryder Nov 25 '20 at 18:22
• Nice. I tried (what seemed to me to be) a simpler approach, but they all seem to end-up the same length... – Dominic van Essen Nov 25 '20 at 20:01
• @DominicvanEssen hang on, this answer has an unnecessary pair of () -- my bad leaving those in! – Giuseppe Nov 25 '20 at 20:45
• @Giuseppe - Drat! You're right! – Dominic van Essen Nov 25 '20 at 20:48

# APL (Dyalog Unicode), 18 bytes (SBCS)

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


Try it online!

A barely-golfed but safe function that outputs the nth element of the sequence.

# APL (Dyalog Unicode), 15 14 bytes (SBCS)

Saved 1 byte thanks to @Adám

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


Try it online!

Outputs the nth element of the sequence. I just realized that this won't work if $$\n = a(n-1)\$$ because it raises n to the power of $$\n - a(n-1)\$$ and multiplies that by $$\a\$$, although as far as I can tell, this function works until at least 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

• Sorry: -2 – Adám Nov 25 '20 at 17:28
• @Adám Oh, cool, that works now. Thanks again! – user Nov 25 '20 at 17:30
• You should probably list ⍤ instead of ö, even if you use the latter as polyfill. That said, ∘ would work here too. – Adám Dec 6 '20 at 14:02
• You're requested a bounty for this, but the OP was posted in 2020. – Adám Dec 6 '20 at 14:08
• @Adám Sorry, I didn’t see that. I’ll remove the request – user Dec 6 '20 at 14:34

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


Try it online!

• Outputs infinite sequence.

Infix operator # computes next term, we use it to fold all positive integers [1..] but using scanl1 instead which gives us all steps.

# Forth (gforth), 82 bytes

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


Try it online!

Outputs an infinite sequence, separated by spaces.

• Nice, was hoping to see a Forth answer on this challenge! – Giuseppe Nov 26 '20 at 4:44

# R, 41 bytes

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


Try it online!

Forced myself not to look at Robin Ryder's R answer before having a go at this. Happily we came up with different approaches to each other, although both seem (so far) to be exactly the same length in bytes sadly for me his one is now 2 bytes shorter...

# C (gcc), 35 bytes

Takes a 1-based starting index and returns the nth sequence value.

f(i,j){i=i?i>(j=f(i-1))?j*i:j/i:1;}


Try it online!

# Perl 5-Minteger-061, 36, 27 bytes

-9 bytes thanks to @Abigail and @Sisyphus.

outputs an infinite sequence

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


Try it online!

• If you add a -061 switch, you can replace $_ with $/ and skip the initial assignment, for 32 bytes. Try it online! – Abigail Nov 25 '20 at 21:06
• I don't know Perl but this seems to work for 31: Try it online! – Sisyphus Nov 25 '20 at 23:22
• @Sisyphus, correct i didn't have much time to golf posted quickly yesterday, and today i can see many other perl 5 answers, don't understand downvote – Nahuel Fouilleul Nov 26 '20 at 8:03
• @NahuelFouilleul I don't understand the downvote either. Have an upvote to compensate =) – Sisyphus Nov 26 '20 at 23:43
• A bunch of the Perl answers to this challenge received a single downvote, no clue why. Only Perl answers were downvoted, although not all of them, oddly. – Giuseppe Nov 27 '20 at 19:11

# Python 3.8+,  45  39 bytes

-2 thanks to xnor (while print(...)!=0:while[print(...)]:)
-4 thanks to 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


A full program which prints $$\a(n)\$$ for all natural numbers.

Try it online!

As a recursive function, 49:

f=lambda v,n=1,a=1:a*(v<n)or f(v,n+1,a//n or a*n)

• – xnor Nov 25 '20 at 20:55
• a:=a//n or a*n saves 4 bytes. – Neil Nov 25 '20 at 21:13
• correct me if I am wrong. So while-loop only functions, if print()-function gives an output other than 0. n+=1 increases n with every iteration. a:=[a*n,a//n][a>n]: define an a where it should be a*n how ever if a>n then it is a//n. Is it correct? Secondly is it the only way to define a partial function via a:=[ ] ? And last when I change a<n it prints always 0. Why does not the loop break? – oakca Nov 26 '20 at 11:32
• @oakca print always returns None, so the !=0 is to make the loop run forever. a:= is inline-assignment, not a function. You are right about what a is assigned to. The loop does not break because it is not meant to - it is supposed to be an infinite loop. – Stephen Nov 26 '20 at 14:15
• Thanks @xnor I think you may have given me the same golf before >.< – Jonathan Allan Nov 27 '20 at 12:33

# JavaScript (Node.js),  38  35 bytes

Saved 3 bytes thanks to @Neil

Returns the $$\n\$$-th term, 1-indexed.

f=(n,k=i=1n)=>i++<n?f(n,k/i||k*i):k


Try it online!

• What's wrong with k/i||k*i? – Neil Nov 25 '20 at 20:01
• @Neil The only thing that's wrong with it is that I didn't think about it. :-p Thank you. – Arnauld Nov 26 '20 at 0:16
• Well, it was bound to happen eventually! – Neil Nov 26 '20 at 0:22
• I love how the syntax highlighting just gives up and makes half of the function body orange and blue :p – Redwolf Programs Nov 30 '20 at 16:17

# Factor, 45 bytes

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


Try it online!

Straightforward reduction. Takes 1-based index and returns the n-th term.

[                         ! 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
]


# K (oK), 22 20 bytes

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


Try it online!

Rather than using $[y>x;y;1%y], indexes into the list (1%y;y) using the boolean condition y>x to save a couple bytes. # Husk, 11 bytes Fμ?*÷<¹³)ḣ  Try it online! 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  • Somehow there's no good way to duplicate 2 arguments.. – Razetime Nov 26 '20 at 3:58 • @Razetime - yes. I tried a lot of variations but couldn't get away from that pesky flip! – Dominic van Essen Nov 26 '20 at 7:36 • F§|*÷ḣ saves four bytes TIO. (Method idea of a logical OR taken from Neil's comment under my Python answer.) – Jonathan Allan Nov 27 '20 at 18:57 • @JonathanAllan - That's much better than mine! You should post it as an answer yourself. – Dominic van Essen Nov 28 '20 at 7:32 • Got it down to six, so posted. – Jonathan Allan Nov 28 '20 at 18:45 # Perl 5-Minteger -p, 35 bytes map$.=$_>$.?$.*$_:$./$_,2..$_;$_=$.  Try it online! Takes n as input and prints the nth item in the list. # 05AB1E, 12 10 bytes Prints the infinite sequence. λN>₁N›i÷ë*  Try it online! Commented: λ # 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  # Forth (gforth), 51 bytes : f 1+ 1 tuck ?do i 2dup <= if * else / then loop ;  Try it online! ### Code Explanation : 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;}  Try it online! Note: Thanks @RedwolfPrograms for -1 Byte and @user for -10(?) bytes. • Welcome to the site! Nice first answer, definitely the shortest Java code I've seen in a while :p – Redwolf Programs Nov 30 '20 at 15:51 • I think you need to add the function header as well. – Razetime Nov 30 '20 at 16:11 • I added the lambda function to prevent any controversies. – DMiddendorf Nov 30 '20 at 19:58 • Very nice. I hope you enjoy your time answering challenges on the site! – Giuseppe Nov 30 '20 at 20:51 • Try i++<n for 1 less byte. – user Nov 30 '20 at 21:17 # Jelly, 11 bytes 1’ß×:>@?$Ị?


Try it online!

## How it works

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

⟦₁{÷ℕ₁|×}ˡ


Try it online!

Gives the singleton list [1] instead of 1 for n = 1, but nothing out of the ordinary otherwise.

         ˡ    Reduce
⟦₁            1 .. n
{     }     by:
÷          integer division
ℕ₁        if the result is 1 or greater,
|×      multiplication if not.


# Gaia, 9 bytes

┅⟪<₌×/?⟫⊢


Try it online!

Basically the same as the shorter Jelly answer. 1-indexed, prints a(n), although ⊢ could be swapped with ⊣ to get the first n elements instead.

		# 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


Try it online! No test suite because of the way the script uses history. Explanation:

K_ _


Replace the input with a pair of 1s (in unary). The first is the loop index while the second is the output.

"$+"+  Loop n times. L$(^_+|_)(?<=(\1)+) (\1)+


Divide both the output and the loop index by the loop index, or by 1 if the division would be zero.

_$$1 $#3*$#2*


Increment the loop index and multiply the two quotients together. This results in output/index*index/index or output/1*index/1 respectively.

r_\G


Convert the final output to decimal.

function a($n){return$n?($n>$x=a($n-1))?$x*$n:$x/$n|0:1;}  Try it online! # cQuents, 14 bytes =1:$>Z?$Z:Z_/$


Try it online!

## Explanation

=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


# Racket, 66 bytes

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


Try it online!

# Wolfram Language (Mathematica), 40 bytes

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


Try it online!

-2 bytes from @att

• 40 bytes – att Nov 26 '20 at 2:01

# J, 21 bytes

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


Try it online!

A J port of @user 's APL solution - don't forget to upvote it!

# MathGolf, 11 9 bytes

1k{î<¿*/


-2 bytes thanks to @ovs.

Outputs the $$\n^{th}\$$ value.

Try it online.

Explanation:

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:

• 10 bytes using ┼. And 9 bytes with ` and some reordering. – ovs Nov 27 '20 at 9:19