33
\$\begingroup\$

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!

\$\endgroup\$

52 Answers 52

18
\$\begingroup\$

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×:<?\
\$\endgroup\$
3
  • 2
    \$\begingroup\$ ...I think I may have overcomplicated mine a bit \$\endgroup\$ Commented Nov 25, 2020 at 18:38
  • 2
    \$\begingroup\$ Yeah, easily done but your solution is still nice IMO. \$\endgroup\$ Commented Nov 25, 2020 at 18:42
  • \$\begingroup\$ Alternatively, R:o×ɗ/, also 6 bytes. \$\endgroup\$
    – jimmy23013
    Commented Jul 1, 2022 at 15:03
15
\$\begingroup\$

Scratch 3.0, 29 27 blocks/234 167 bytes

enter image description here

As 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)

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

\$\endgroup\$
3
  • 8
    \$\begingroup\$ 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. \$\endgroup\$
    – user
    Commented Nov 25, 2020 at 23:40
  • \$\begingroup\$ 167 bytes \$\endgroup\$
    – att
    Commented Nov 26, 2020 at 7:02
  • 1
    \$\begingroup\$ @downvoter why? \$\endgroup\$
    – lyxal
    Commented Nov 28, 2020 at 3:33
14
\$\begingroup\$

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!

\$\endgroup\$
12
\$\begingroup\$

Python 2, 47 43 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.

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

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<a(n-1)}} -1}}\right\rfloor $$

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

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

Haskell, 40 bytes

a#n|n>a=a*n|1>0=a`div`n
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.

\$\endgroup\$
8
\$\begingroup\$

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ Nice, was hoping to see a Forth answer on this challenge! \$\endgroup\$
    – Giuseppe
    Commented Nov 26, 2020 at 4:44
8
\$\begingroup\$

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)
\$\endgroup\$
6
  • \$\begingroup\$ 43: Try it online! \$\endgroup\$
    – xnor
    Commented Nov 25, 2020 at 20:55
  • \$\begingroup\$ a:=a//n or a*n saves 4 bytes. \$\endgroup\$
    – Neil
    Commented Nov 25, 2020 at 21:13
  • \$\begingroup\$ 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? \$\endgroup\$
    – oakca
    Commented Nov 26, 2020 at 11:32
  • \$\begingroup\$ @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. \$\endgroup\$
    – Stephen
    Commented Nov 26, 2020 at 14:15
  • \$\begingroup\$ Thanks @xnor I think you may have given me the same golf before >.< \$\endgroup\$ Commented Nov 27, 2020 at 12:33
7
\$\begingroup\$

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

\$\endgroup\$
7
\$\begingroup\$

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!

\$\endgroup\$
7
\$\begingroup\$

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!

\$\endgroup\$
5
  • \$\begingroup\$ If you add a -061 switch, you can replace $_ with $/ and skip the initial assignment, for 32 bytes. Try it online! \$\endgroup\$
    – Abigail
    Commented Nov 25, 2020 at 21:06
  • \$\begingroup\$ I don't know Perl but this seems to work for 31: Try it online! \$\endgroup\$
    – Sisyphus
    Commented Nov 25, 2020 at 23:22
  • \$\begingroup\$ @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 \$\endgroup\$ Commented Nov 26, 2020 at 8:03
  • \$\begingroup\$ @NahuelFouilleul I don't understand the downvote either. Have an upvote to compensate =) \$\endgroup\$
    – Sisyphus
    Commented Nov 26, 2020 at 23:43
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Giuseppe
    Commented Nov 27, 2020 at 19:11
6
\$\begingroup\$

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!

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

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
]
\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
5
  • \$\begingroup\$ Somehow there's no good way to duplicate 2 arguments.. \$\endgroup\$
    – Razetime
    Commented Nov 26, 2020 at 3:58
  • 1
    \$\begingroup\$ @Razetime - yes. I tried a lot of variations but couldn't get away from that pesky flip! \$\endgroup\$ Commented Nov 26, 2020 at 7:36
  • 2
    \$\begingroup\$ F§|*`÷ḣ saves four bytes TIO. (Method idea of a logical OR taken from Neil's comment under my Python answer.) \$\endgroup\$ Commented Nov 27, 2020 at 18:57
  • \$\begingroup\$ @JonathanAllan - That's much better than mine! You should post it as an answer yourself. \$\endgroup\$ Commented Nov 28, 2020 at 7:32
  • \$\begingroup\$ Got it down to six, so posted. \$\endgroup\$ Commented Nov 28, 2020 at 18:45
5
\$\begingroup\$

Perl 5 -Minteger -p, 35 bytes

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

Try it online!

Takes n as input and prints the nth item in the list.

\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
12
  • \$\begingroup\$ Welcome to the site! Nice first answer, definitely the shortest Java code I've seen in a while :p \$\endgroup\$
    – rydwolf
    Commented Nov 30, 2020 at 15:51
  • 1
    \$\begingroup\$ I think you need to add the function header as well. \$\endgroup\$
    – Razetime
    Commented Nov 30, 2020 at 16:11
  • 1
    \$\begingroup\$ I added the lambda function to prevent any controversies. \$\endgroup\$ Commented Nov 30, 2020 at 19:58
  • 1
    \$\begingroup\$ Very nice. I hope you enjoy your time answering challenges on the site! \$\endgroup\$
    – Giuseppe
    Commented Nov 30, 2020 at 20:51
  • 1
    \$\begingroup\$ Try i++<n for 1 less byte. \$\endgroup\$
    – user
    Commented Nov 30, 2020 at 21:17
4
\$\begingroup\$

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)
\$\endgroup\$
4
\$\begingroup\$

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.
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

PHP, 57 bytes

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

Try it online!

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

Racket, 66 bytes

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

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Wolfram Language (Mathematica), 40 bytes

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

Try it online!

-2 bytes from @att

\$\endgroup\$
1
  • \$\begingroup\$ 40 bytes \$\endgroup\$
    – att
    Commented Nov 26, 2020 at 2:01
4
\$\begingroup\$

J, 21 bytes

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

Try it online!

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

\$\endgroup\$
4
\$\begingroup\$

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:
       /  #   Integer-divide instead
          # (after the loop, the entire stack joined together is output implicitly)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 10 bytes using . And 9 bytes with ` and some reordering. \$\endgroup\$
    – ovs
    Commented Nov 27, 2020 at 9:19
  • \$\begingroup\$ @ovs Oh, I was not even aware of either of those two builtins! o.Ô Thanks \$\endgroup\$ Commented Nov 27, 2020 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.